///////////////////////////////////////////////////////////////////////////////
// Simple x264 Launcher
-// Copyright (C) 2004-2013 LoRd_MuldeR <MuldeR2@GMX.de>
+// Copyright (C) 2004-2020 LoRd_MuldeR <MuldeR2@GMX.de>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
///////////////////////////////////////////////////////////////////////////////
#include "win_main.h"
-
+#include "UIC_win_main.h"
+
+//Internal
+#include "global.h"
+#include "cli.h"
+#include "ipc.h"
+#include "model_status.h"
+#include "model_sysinfo.h"
#include "model_jobList.h"
#include "model_options.h"
#include "model_preferences.h"
#include "model_recently.h"
#include "thread_avisynth.h"
-#include "thread_ipc.h"
+#include "thread_binaries.h"
+#include "thread_vapoursynth.h"
#include "thread_encode.h"
-#include "taskbar7.h"
+#include "thread_ipc_recv.h"
+#include "input_filter.h"
#include "win_addJob.h"
+#include "win_about.h"
#include "win_preferences.h"
+#include "win_updater.h"
#include "resource.h"
+//MUtils
+#include <MUtils/OSSupport.h>
+#include <MUtils/CPUFeatures.h>
+#include <MUtils/IPCChannel.h>
+#include <MUtils/GUI.h>
+#include <MUtils/Sound.h>
+#include <MUtils/Exception.h>
+#include <MUtils/Taskbar7.h>
+#include <MUtils/Version.h>
+
+//Qt
#include <QDate>
#include <QTimer>
#include <QCloseEvent>
#include <QTextStream>
#include <QSettings>
#include <QFileDialog>
-
-#include <Mmsystem.h>
-
-const char *home_url = "http://muldersoft.com/";
-const char *update_url = "http://code.google.com/p/mulder/downloads/list";
-const char *tpl_last = "<LAST_USED>";
-
-#define SET_FONT_BOLD(WIDGET,BOLD) { QFont _font = WIDGET->font(); _font.setBold(BOLD); WIDGET->setFont(_font); }
-#define SET_TEXT_COLOR(WIDGET,COLOR) { QPalette _palette = WIDGET->palette(); _palette.setColor(QPalette::WindowText, (COLOR)); _palette.setColor(QPalette::Text, (COLOR)); WIDGET->setPalette(_palette); }
-
-static int exceptionFilter(_EXCEPTION_RECORD *dst, _EXCEPTION_POINTERS *src) { memcpy(dst, src->ExceptionRecord, sizeof(_EXCEPTION_RECORD)); return EXCEPTION_EXECUTE_HANDLER; }
+#include <QSystemTrayIcon>
+#include <QMovie>
+#include <QTextDocument>
+#include <ctime>
+
+//Constants
+static const char *tpl_last = "<LAST_USED>";
+static const char *home_url = "http://muldersoft.com/";
+static const char *update_url = "https://github.com/lordmulder/Simple-x264-Launcher/releases/latest";
+static const char *avs_dl_url = "http://sourceforge.net/projects/avisynth2/files/AviSynth%202.5/";
+static const char *python_url = "https://www.python.org/downloads/";
+static const char *vsynth_url = "http://www.vapoursynth.com/";
+static const int vsynth_rev = 24;
+
+//Macros
+#define SET_FONT_BOLD(WIDGET,BOLD) do { QFont _font = WIDGET->font(); _font.setBold(BOLD); WIDGET->setFont(_font); } while(0)
+#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)
+#define LINK(URL) (QString("<a href=\"%1\">%1</a>").arg((URL)))
+#define INIT_ERROR_EXIT() do { close(); qApp->exit(-1); return; } while(0)
+#define SETUP_WEBLINK(OBJ, URL) do { (OBJ)->setData(QVariant(QUrl(URL))); connect((OBJ), SIGNAL(triggered()), this, SLOT(showWebLink())); } while(0)
+#define APP_IS_READY (m_initialized && (!m_fileTimer->isActive()) && (QApplication::activeModalWidget() == NULL))
+#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)
+#define X264_STRCMP(X,Y) ((X).compare((Y), Qt::CaseInsensitive) == 0)
///////////////////////////////////////////////////////////////////////////////
// Constructor & Destructor
/*
* Constructor
*/
-MainWindow::MainWindow(const x264_cpu_t *const cpuFeatures)
+MainWindow::MainWindow(const MUtils::CPUFetaures::cpu_info_t &cpuFeatures, MUtils::IPCChannel *const ipcChannel)
:
- m_cpuFeatures(cpuFeatures),
- m_appDir(QApplication::applicationDirPath()),
+ m_ipcChannel(ipcChannel),
+ m_sysinfo(NULL),
m_options(NULL),
m_jobList(NULL),
- m_droppedFiles(NULL),
+ m_pendingFiles(new QStringList()),
m_preferences(NULL),
m_recentlyUsed(NULL),
- m_skipVersionTest(false),
- m_abortOnTimeout(true),
- m_firstShow(true)
+ m_postOperation(POST_OP_DONOTHING),
+ m_initialized(false),
+ ui(new Ui::MainWindow())
{
//Init the dialog, from the .ui file
- setupUi(this);
+ ui->setupUi(this);
setWindowFlags(windowFlags() & (~Qt::WindowMaximizeButtonHint));
//Register meta types
qRegisterMetaType<QUuid>("DWORD");
qRegisterMetaType<JobStatus>("JobStatus");
+ //Create and initialize the sysinfo object
+ m_sysinfo.reset(new SysinfoModel());
+ m_sysinfo->setAppPath(QApplication::applicationDirPath());
+ m_sysinfo->setCPUFeatures(SysinfoModel::CPUFeatures_MMX, cpuFeatures.features & MUtils::CPUFetaures::FLAG_MMX);
+ m_sysinfo->setCPUFeatures(SysinfoModel::CPUFeatures_SSE, cpuFeatures.features & MUtils::CPUFetaures::FLAG_SSE);
+ m_sysinfo->setCPUFeatures(SysinfoModel::CPUFeatures_X64, cpuFeatures.x64 && (cpuFeatures.features & MUtils::CPUFetaures::FLAG_SSE2)); //X64 implies SSE2
+
//Load preferences
- m_preferences = new PreferencesModel();
- PreferencesModel::loadPreferences(m_preferences);
+ m_preferences.reset(new PreferencesModel());
+ PreferencesModel::loadPreferences(m_preferences.data());
//Load recently used
- m_recentlyUsed = new RecentlyUsed();
- RecentlyUsed::loadRecentlyUsed(m_recentlyUsed);
+ m_recentlyUsed.reset(new RecentlyUsed());
+ RecentlyUsed::loadRecentlyUsed(m_recentlyUsed.data());
//Create options object
- m_options = new OptionsModel();
- OptionsModel::loadTemplate(m_options, QString::fromLatin1(tpl_last));
+ m_options.reset(new OptionsModel(m_sysinfo.data()));
+ OptionsModel::loadTemplate(m_options.data(), QString::fromLatin1(tpl_last));
- //Create IPC thread object
- m_ipcThread = new IPCThread();
- connect(m_ipcThread, SIGNAL(instanceCreated(DWORD)), this, SLOT(instanceCreated(DWORD)), Qt::QueuedConnection);
+ //DPI scaling
+ MUtils::GUI::scale_widget(this);
//Freeze minimum size
setMinimumSize(size());
- splitter->setSizes(QList<int>() << 16 << 196);
+ ui->splitter->setSizes(QList<int>() << 16 << 196);
//Update title
- labelBuildDate->setText(tr("Built on %1 at %2").arg(x264_version_date().toString(Qt::ISODate), QString::fromLatin1(x264_version_time())));
- labelBuildDate->installEventFilter(this);
- setWindowTitle(QString("%1 (%2 Mode)").arg(windowTitle(), m_cpuFeatures->x64 ? "64-Bit" : "32-Bit"));
- if(X264_DEBUG)
+ 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)));
+
+ if(MUTILS_DEBUG)
{
setWindowTitle(QString("%1 | !!! DEBUG VERSION !!!").arg(windowTitle()));
setStyleSheet("QMenuBar, QMainWindow { background-color: yellow }");
}
//Create model
- m_jobList = new JobListModel(m_preferences);
- connect(m_jobList, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(jobChangedData(QModelIndex, QModelIndex)));
- jobsView->setModel(m_jobList);
+ m_jobList.reset(new JobListModel(m_preferences.data()));
+ connect(m_jobList.data(), SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(jobChangedData(QModelIndex, QModelIndex)));
+ ui->jobsView->setModel(m_jobList.data());
//Setup view
- jobsView->horizontalHeader()->setSectionHidden(3, true);
- jobsView->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
- jobsView->horizontalHeader()->setResizeMode(1, QHeaderView::Fixed);
- jobsView->horizontalHeader()->setResizeMode(2, QHeaderView::Fixed);
- jobsView->horizontalHeader()->resizeSection(1, 150);
- jobsView->horizontalHeader()->resizeSection(2, 90);
- jobsView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
- connect(jobsView->selectionModel(), SIGNAL(currentChanged(QModelIndex, QModelIndex)), this, SLOT(jobSelected(QModelIndex, QModelIndex)));
+ ui->jobsView->horizontalHeader()->setSectionHidden(3, true);
+ ui->jobsView->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
+ ui->jobsView->horizontalHeader()->setResizeMode(1, QHeaderView::ResizeToContents);
+ ui->jobsView->horizontalHeader()->setResizeMode(2, QHeaderView::ResizeToContents);
+ ui->jobsView->horizontalHeader()->setMinimumSectionSize(96);
+ ui->jobsView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
+ connect(ui->jobsView->selectionModel(), SIGNAL(currentChanged(QModelIndex, QModelIndex)), this, SLOT(jobSelected(QModelIndex, QModelIndex)));
+
+ //Setup key listener
+ m_inputFilter_jobList.reset(new InputEventFilter(ui->jobsView));
+ m_inputFilter_jobList->addKeyFilter(Qt::ControlModifier | Qt::Key_Up, 1);
+ m_inputFilter_jobList->addKeyFilter(Qt::ControlModifier | Qt::Key_Down, 2);
+ connect(m_inputFilter_jobList.data(), SIGNAL(keyPressed(int)), this, SLOT(jobListKeyPressed(int)));
+
+ //Setup mouse listener
+ m_inputFilter_version.reset(new InputEventFilter(ui->labelBuildDate));
+ m_inputFilter_version->addMouseFilter(Qt::LeftButton, 0);
+ m_inputFilter_version->addMouseFilter(Qt::RightButton, 0);
+ connect(m_inputFilter_version.data(), SIGNAL(mouseClicked(int)), this, SLOT(versionLabelMouseClicked(int)));
//Create context menu
- QAction *actionClipboard = new QAction(QIcon(":/buttons/page_paste.png"), tr("Copy to Clipboard"), logView);
+ QAction *actionClipboard = new QAction(QIcon(":/buttons/page_paste.png"), tr("Copy to Clipboard"), ui->logView);
+ QAction *actionSaveToLog = new QAction(QIcon(":/buttons/disk.png"), tr("Save to File..."), ui->logView);
+ QAction *actionSeparator = new QAction(ui->logView);
+ QAction *actionWordwraps = new QAction(QIcon(":/buttons/text_wrapping.png"), tr("Enable Line-Wrapping"), ui->logView);
+ actionSeparator->setSeparator(true);
+ actionWordwraps->setCheckable(true);
actionClipboard->setEnabled(false);
- logView->addAction(actionClipboard);
+ actionSaveToLog->setEnabled(false);
+ actionWordwraps->setEnabled(false);
+ ui->logView->addAction(actionClipboard);
+ ui->logView->addAction(actionSaveToLog);
+ ui->logView->addAction(actionSeparator);
+ ui->logView->addAction(actionWordwraps);
connect(actionClipboard, SIGNAL(triggered(bool)), this, SLOT(copyLogToClipboard(bool)));
- jobsView->addActions(menuJob->actions());
+ connect(actionSaveToLog, SIGNAL(triggered(bool)), this, SLOT(saveLogToLocalFile(bool)));
+ connect(actionWordwraps, SIGNAL(triggered(bool)), this, SLOT(toggleLineWrapping(bool)));
+ ui->jobsView->addActions(ui->menuJob->actions());
//Enable buttons
- connect(buttonAddJob, SIGNAL(clicked()), this, SLOT(addButtonPressed()));
- connect(buttonStartJob, SIGNAL(clicked()), this, SLOT(startButtonPressed()));
- connect(buttonAbortJob, SIGNAL(clicked()), this, SLOT(abortButtonPressed()));
- connect(buttonPauseJob, SIGNAL(toggled(bool)), this, SLOT(pauseButtonPressed(bool)));
- connect(actionJob_Delete, SIGNAL(triggered()), this, SLOT(deleteButtonPressed()));
- connect(actionJob_Restart, SIGNAL(triggered()), this, SLOT(restartButtonPressed()));
- connect(actionJob_Browse, SIGNAL(triggered()), this, SLOT(browseButtonPressed()));
+ connect(ui->buttonAddJob, SIGNAL(clicked()), this, SLOT(addButtonPressed() ));
+ connect(ui->buttonStartJob, SIGNAL(clicked()), this, SLOT(startButtonPressed() ));
+ connect(ui->buttonAbortJob, SIGNAL(clicked()), this, SLOT(abortButtonPressed() ));
+ connect(ui->buttonPauseJob, SIGNAL(toggled(bool)), this, SLOT(pauseButtonPressed(bool)));
+ connect(ui->actionJob_Delete, SIGNAL(triggered()), this, SLOT(deleteButtonPressed() ));
+ connect(ui->actionJob_Restart, SIGNAL(triggered()), this, SLOT(restartButtonPressed() ));
+ connect(ui->actionJob_Browse, SIGNAL(triggered()), this, SLOT(browseButtonPressed() ));
+ connect(ui->actionJob_MoveUp, SIGNAL(triggered()), this, SLOT(moveButtonPressed() ));
+ connect(ui->actionJob_MoveDown, SIGNAL(triggered()), this, SLOT(moveButtonPressed() ));
//Enable menu
- connect(actionOpen, SIGNAL(triggered()), this, SLOT(openActionTriggered()));
- connect(actionAbout, SIGNAL(triggered()), this, SLOT(showAbout()));
- connect(actionWebMulder, SIGNAL(triggered()), this, SLOT(showWebLink()));
- connect(actionWebX264, SIGNAL(triggered()), this, SLOT(showWebLink()));
- connect(actionWebKomisar, SIGNAL(triggered()), this, SLOT(showWebLink()));
- connect(actionWebJarod, SIGNAL(triggered()), this, SLOT(showWebLink()));
- connect(actionWebJEEB, SIGNAL(triggered()), this, SLOT(showWebLink()));
- connect(actionWebAvisynth32, SIGNAL(triggered()), this, SLOT(showWebLink()));
- connect(actionWebAvisynth64, SIGNAL(triggered()), this, SLOT(showWebLink()));
- connect(actionWebWiki, SIGNAL(triggered()), this, SLOT(showWebLink()));
- connect(actionWebBluRay, SIGNAL(triggered()), this, SLOT(showWebLink()));
- connect(actionWebAvsWiki, SIGNAL(triggered()), this, SLOT(showWebLink()));
- connect(actionWebSecret, SIGNAL(triggered()), this, SLOT(showWebLink()));
- connect(actionWebSupport, SIGNAL(triggered()), this, SLOT(showWebLink()));
- connect(actionPreferences, SIGNAL(triggered()), this, SLOT(showPreferences()));
+ connect(ui->actionOpen, SIGNAL(triggered()), this, SLOT(openActionTriggered()));
+ connect(ui->actionCleanup_Finished, SIGNAL(triggered()), this, SLOT(cleanupActionTriggered()));
+ connect(ui->actionCleanup_Enqueued, SIGNAL(triggered()), this, SLOT(cleanupActionTriggered()));
+ connect(ui->actionPostOp_DoNothing, SIGNAL(triggered()), this, SLOT(postOpActionTriggered()));
+ connect(ui->actionPostOp_PowerDown, SIGNAL(triggered()), this, SLOT(postOpActionTriggered()));
+ connect(ui->actionPostOp_Hibernate, SIGNAL(triggered()), this, SLOT(postOpActionTriggered()));
+ connect(ui->actionAbout, SIGNAL(triggered()), this, SLOT(showAbout()));
+ connect(ui->actionPreferences, SIGNAL(triggered()), this, SLOT(showPreferences()));
+ connect(ui->actionCheckForUpdates, SIGNAL(triggered()), this, SLOT(checkUpdates()));
+ ui->actionCleanup_Finished->setData(QVariant(bool(0)));
+ ui->actionCleanup_Enqueued->setData(QVariant(bool(1)));
+ ui->actionPostOp_DoNothing->setData(QVariant(POST_OP_DONOTHING));
+ ui->actionPostOp_PowerDown->setData(QVariant(POST_OP_POWERDOWN));
+ ui->actionPostOp_Hibernate->setData(QVariant(POST_OP_HIBERNATE));
+ ui->actionPostOp_Hibernate->setEnabled(MUtils::OS::is_hibernation_supported());
+
+ //Setup web-links
+ SETUP_WEBLINK(ui->actionWebMulder, home_url);
+ SETUP_WEBLINK(ui->actionWebX264, "http://www.videolan.org/developers/x264.html");
+ SETUP_WEBLINK(ui->actionWebX265, "http://www.videolan.org/developers/x265.html");
+ SETUP_WEBLINK(ui->actionWebX264LigH, "http://www.mediafire.com/?bxvu1vvld31k1");
+ SETUP_WEBLINK(ui->actionWebX264VideoLAN, "http://artifacts.videolan.org/x264/");
+ SETUP_WEBLINK(ui->actionWebX264Komisar, "http://komisar.gin.by/");
+ SETUP_WEBLINK(ui->actionWebX265LigH, "http://www.mediafire.com/?6lfp2jlygogwa");
+ SETUP_WEBLINK(ui->actionWebX264FreeCodecs, "http://www.free-codecs.com/x264_video_codec_download.htm");
+ SETUP_WEBLINK(ui->actionWebX265Fllear, "http://x265.ru/en/builds/");
+ SETUP_WEBLINK(ui->actionWebX265Snowfag, "http://builds.x265.eu/");
+ SETUP_WEBLINK(ui->actionWebX265FreeCodecs, "http://www.free-codecs.com/x265_hevc_encoder_download.htm");
+ SETUP_WEBLINK(ui->actionWebAvisynth32, "https://sourceforge.net/projects/avisynth2/files/AviSynth%202.6/");
+ SETUP_WEBLINK(ui->actionWebAvisynth64, "http://forum.doom9.org/showthread.php?t=152800");
+ SETUP_WEBLINK(ui->actionWebAvisynthPlus, "http://www.avs-plus.net/");
+ SETUP_WEBLINK(ui->actionWebVapourSynth, "http://www.vapoursynth.com/");
+ SETUP_WEBLINK(ui->actionWebVapourSynthDocs, "http://www.vapoursynth.com/doc/");
+ SETUP_WEBLINK(ui->actionOnlineDocX264, "http://en.wikibooks.org/wiki/MeGUI/x264_Settings"); //http://mewiki.project357.com/wiki/X264_Settings
+ SETUP_WEBLINK(ui->actionOnlineDocX265, "http://x265.readthedocs.org/en/default/");
+ SETUP_WEBLINK(ui->actionWebBluRay, "http://www.x264bluray.com/");
+ SETUP_WEBLINK(ui->actionWebAvsWiki, "http://avisynth.nl/index.php/Main_Page#Usage");
+ SETUP_WEBLINK(ui->actionWebSupport, "http://forum.doom9.org/showthread.php?t=144140");
+ SETUP_WEBLINK(ui->actionWebSecret, "http://www.youtube.com/watch_popup?v=AXIeHY-OYNI");
//Create floating label
- m_label = new QLabel(jobsView->viewport());
- m_label->setText(tr("No job created yet. Please click the 'Add New Job' button!"));
- m_label->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
- SET_TEXT_COLOR(m_label, Qt::darkGray);
- SET_FONT_BOLD(m_label, true);
- m_label->setVisible(true);
- m_label->setContextMenuPolicy(Qt::ActionsContextMenu);
- m_label->addActions(jobsView->actions());
- connect(splitter, SIGNAL(splitterMoved(int, int)), this, SLOT(updateLabelPos()));
+ m_label[0].reset(new QLabel(ui->jobsView->viewport()));
+ m_label[1].reset(new QLabel(ui->logView->viewport()));
+ if(!m_label[0].isNull())
+ {
+ m_label[0]->setText(tr("No job created yet. Please click the 'Add New Job' button!"));
+ m_label[0]->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
+ SET_TEXT_COLOR(m_label[0], Qt::darkGray);
+ SET_FONT_BOLD(m_label[0], true);
+ m_label[0]->setVisible(true);
+ m_label[0]->setContextMenuPolicy(Qt::ActionsContextMenu);
+ m_label[0]->addActions(ui->jobsView->actions());
+ }
+ if(!m_label[1].isNull())
+ {
+ m_animation.reset(new QMovie(":/images/spinner.gif"));
+ m_label[1]->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
+ if(!m_animation.isNull())
+ {
+ m_label[1]->setMovie(m_animation.data());
+ m_animation->start();
+ }
+ }
+ connect(ui->splitter, SIGNAL(splitterMoved(int, int)), this, SLOT(updateLabelPos()));
updateLabelPos();
+
+ //Init system tray icon
+ m_sysTray.reset(new QSystemTrayIcon(this));
+ m_sysTray->setToolTip(this->windowTitle());
+ m_sysTray->setIcon(this->windowIcon());
+ connect(m_sysTray.data(), SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(sysTrayActived()));
+
+ //Init taskbar progress
+ m_taskbar.reset(new MUtils::Taskbar7(this));
+
+ //Create corner widget
+ QLabel *checkUp = new QLabel(ui->menubar);
+ checkUp->setText(QString("<nobr><img src=\":/buttons/exclamation_small.png\"> <b style=\"color:darkred\">%1</b> </nobr>").arg(tr("Check for Updates")));
+ checkUp->setFixedHeight(ui->menubar->height());
+ checkUp->setCursor(QCursor(Qt::PointingHandCursor));
+ m_inputFilter_checkUp.reset(new InputEventFilter(checkUp));
+ m_inputFilter_checkUp->addMouseFilter(Qt::LeftButton, 0);
+ m_inputFilter_checkUp->addMouseFilter(Qt::RightButton, 0);
+ connect(m_inputFilter_checkUp.data(), SIGNAL(mouseClicked(int)), this, SLOT(checkUpdates()));
+ checkUp->hide();
+ ui->menubar->setCornerWidget(checkUp);
+
+ //Create timer
+ m_fileTimer.reset(new QTimer(this));
+ connect(m_fileTimer.data(), SIGNAL(timeout()), this, SLOT(handlePendingFiles()));
}
/*
*/
MainWindow::~MainWindow(void)
{
- OptionsModel::saveTemplate(m_options, QString::fromLatin1(tpl_last));
+ OptionsModel::saveTemplate(m_options.data(), QString::fromLatin1(tpl_last));
- X264_DELETE(m_jobList);
- X264_DELETE(m_options);
- X264_DELETE(m_droppedFiles);
- X264_DELETE(m_label);
-
- while(!m_toolsList.isEmpty())
+ if(!m_ipcThread.isNull())
{
- QFile *temp = m_toolsList.takeFirst();
- X264_DELETE(temp);
- }
-
- if(m_ipcThread->isRunning())
- {
- m_ipcThread->setAbort();
+ m_ipcThread->stop();
if(!m_ipcThread->wait(5000))
{
m_ipcThread->terminate();
}
}
- X264_DELETE(m_ipcThread);
- AvisynthCheckThread::unload();
- X264_DELETE(m_preferences);
- X264_DELETE(m_recentlyUsed);
+ delete ui;
}
///////////////////////////////////////////////////////////////////////////////
*/
void MainWindow::addButtonPressed()
{
+ ENSURE_APP_IS_READY();
+
qDebug("MainWindow::addButtonPressed");
- bool runImmediately = (countRunningJobs() < (m_preferences->autoRunNextJob() ? m_preferences->maxRunningJobCount() : 1));
+ bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
QString sourceFileName, outputFileName;
-
- if(createJob(sourceFileName, outputFileName, m_options, runImmediately))
+
+ if(createJob(sourceFileName, outputFileName, m_options.data(), runImmediately))
{
- appendJob(sourceFileName, outputFileName, m_options, runImmediately);
+ appendJob(sourceFileName, outputFileName, m_options.data(), runImmediately);
}
}
*/
void MainWindow::openActionTriggered()
{
+ ENSURE_APP_IS_READY();
+ qWarning("openActionTriggered()");
+
QStringList fileList = QFileDialog::getOpenFileNames(this, tr("Open Source File(s)"), m_recentlyUsed->sourceDirectory(), AddJobDialog::getInputFilterLst(), NULL, QFileDialog::DontUseNativeDialog);
if(!fileList.empty())
{
}
else
{
- bool runImmediately = (countRunningJobs() < (m_preferences->autoRunNextJob() ? m_preferences->maxRunningJobCount() : 1));
+ bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
QString sourceFileName(fileList.first()), outputFileName;
- if(createJob(sourceFileName, outputFileName, m_options, runImmediately))
+ if(createJob(sourceFileName, outputFileName, m_options.data(), runImmediately))
{
- appendJob(sourceFileName, outputFileName, m_options, runImmediately);
+ appendJob(sourceFileName, outputFileName, m_options.data(), runImmediately);
+ }
+ }
+ }
+}
+
+/*
+* The "clean-up" action was invoked
+*/
+void MainWindow::cleanupActionTriggered(void)
+{
+ ENSURE_APP_IS_READY();
+
+ QAction *const sender = dynamic_cast<QAction*>(QObject::sender());
+ if (sender)
+ {
+ const QVariant data = sender->data();
+ if (data.isValid() && (data.type() == QVariant::Bool))
+ {
+ const bool mode = data.toBool();
+ const int rows = m_jobList->rowCount(QModelIndex());
+ QList<int> jobIndices;
+ for (int i = 0; i < rows; i++)
+ {
+ const JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
+ if (mode && (status == JobStatus_Enqueued))
+ {
+ jobIndices.append(i);
+ }
+ else if ((!mode) && ((status == JobStatus_Completed) || (status == JobStatus_Aborted) || (status == JobStatus_Failed)))
+ {
+ jobIndices.append(i);
+ }
+ }
+ if (!jobIndices.isEmpty())
+ {
+ QListIterator<int> iter(jobIndices);
+ iter.toBack();
+ while(iter.hasPrevious())
+ {
+ m_jobList->deleteJob(m_jobList->index(iter.previous(), 0, QModelIndex()));
+ }
+ }
+ else
+ {
+ MUtils::Sound::beep(MUtils::Sound::BEEP_WRN);
+ }
+ }
+ }
+}
+
+/*
+* The "clean-up" action was invoked
+*/
+void MainWindow::postOpActionTriggered(void)
+{
+ ENSURE_APP_IS_READY();
+
+ QAction *const sender = dynamic_cast<QAction*>(QObject::sender());
+ if (sender)
+ {
+ const QVariant data = sender->data();
+ if (data.isValid() && (data.type() == QVariant::Int))
+ {
+ const postOp_t mode = (postOp_t)data.toInt();
+ if ((mode >= POST_OP_DONOTHING) && (mode <= POST_OP_HIBERNATE))
+ {
+ m_postOperation = mode;
+ ui->actionPostOp_PowerDown->setChecked(mode == POST_OP_POWERDOWN);
+ ui->actionPostOp_Hibernate->setChecked(mode == POST_OP_HIBERNATE);
+ ui->actionPostOp_DoNothing->setChecked(mode == POST_OP_DONOTHING);
}
}
}
*/
void MainWindow::startButtonPressed(void)
{
- m_jobList->startJob(jobsView->currentIndex());
+ ENSURE_APP_IS_READY();
+ m_jobList->startJob(ui->jobsView->currentIndex());
}
/*
*/
void MainWindow::abortButtonPressed(void)
{
- m_jobList->abortJob(jobsView->currentIndex());
+ ENSURE_APP_IS_READY();
+
+ 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)
+ {
+ m_jobList->abortJob(ui->jobsView->currentIndex());
+ }
}
/*
*/
void MainWindow::deleteButtonPressed(void)
{
- m_jobList->deleteJob(jobsView->currentIndex());
- m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
+ ENSURE_APP_IS_READY();
+
+ m_jobList->deleteJob(ui->jobsView->currentIndex());
+ m_label[0]->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
}
/*
*/
void MainWindow::browseButtonPressed(void)
{
- QString outputFile = m_jobList->getJobOutputFile(jobsView->currentIndex());
+ ENSURE_APP_IS_READY();
+
+ QString outputFile = m_jobList->getJobOutputFile(ui->jobsView->currentIndex());
if((!outputFile.isEmpty()) && QFileInfo(outputFile).exists() && QFileInfo(outputFile).isFile())
{
QProcess::startDetached(QString::fromLatin1("explorer.exe"), QStringList() << QString::fromLatin1("/select,") << QDir::toNativeSeparators(outputFile), QFileInfo(outputFile).path());
}
/*
+ * The "browse" button was clicked
+ */
+void MainWindow::moveButtonPressed(void)
+{
+ ENSURE_APP_IS_READY();
+
+ if(sender() == ui->actionJob_MoveUp)
+ {
+ qDebug("Move job %d (direction: UP)", ui->jobsView->currentIndex().row());
+ if(!m_jobList->moveJob(ui->jobsView->currentIndex(), JobListModel::MOVE_UP))
+ {
+ MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
+ }
+ ui->jobsView->scrollTo(ui->jobsView->currentIndex(), QAbstractItemView::PositionAtCenter);
+ }
+ else if(sender() == ui->actionJob_MoveDown)
+ {
+ qDebug("Move job %d (direction: DOWN)", ui->jobsView->currentIndex().row());
+ if(!m_jobList->moveJob(ui->jobsView->currentIndex(), JobListModel::MOVE_DOWN))
+ {
+ MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
+ }
+ ui->jobsView->scrollTo(ui->jobsView->currentIndex(), QAbstractItemView::PositionAtCenter);
+ }
+ else
+ {
+ qWarning("[moveButtonPressed] Error: Unknown sender!");
+ }
+}
+
+/*
* The "pause" button was clicked
*/
void MainWindow::pauseButtonPressed(bool checked)
{
+ if(!APP_IS_READY)
+ {
+ MUtils::Sound::beep(MUtils::Sound::BEEP_WRN);
+ qWarning("Cannot perfrom this action at this time!");
+ ui->buttonPauseJob->setChecked(!checked);
+ }
+
if(checked)
{
- m_jobList->pauseJob(jobsView->currentIndex());
+ m_jobList->pauseJob(ui->jobsView->currentIndex());
}
else
{
- m_jobList->resumeJob(jobsView->currentIndex());
+ m_jobList->resumeJob(ui->jobsView->currentIndex());
}
}
*/
void MainWindow::restartButtonPressed(void)
{
- const QModelIndex index = jobsView->currentIndex();
+ ENSURE_APP_IS_READY();
+
+ const QModelIndex index = ui->jobsView->currentIndex();
const OptionsModel *options = m_jobList->getJobOptions(index);
QString sourceFileName = m_jobList->getJobSourceFile(index);
QString outputFileName = m_jobList->getJobOutputFile(index);
if((options) && (!sourceFileName.isEmpty()) && (!outputFileName.isEmpty()))
{
- bool runImmediately = true;
+ bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
OptionsModel *tempOptions = new OptionsModel(*options);
if(createJob(sourceFileName, outputFileName, tempOptions, runImmediately, true))
{
appendJob(sourceFileName, outputFileName, tempOptions, runImmediately);
}
- X264_DELETE(tempOptions);
+ MUTILS_DELETE(tempOptions);
}
}
{
qDebug("Job selected: %d", current.row());
- if(logView->model())
+ if(ui->logView->model())
{
- disconnect(logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
+ disconnect(ui->logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
}
if(current.isValid())
{
- logView->setModel(m_jobList->getLogFile(current));
- connect(logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
- logView->actions().first()->setEnabled(true);
- QTimer::singleShot(0, logView, SLOT(scrollToBottom()));
+ ui->logView->setModel(m_jobList->getLogFile(current));
+ connect(ui->logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
+ foreach(QAction *action, ui->logView->actions())
+ {
+ action->setEnabled(true);
+ }
+ QTimer::singleShot(0, ui->logView, SLOT(scrollToBottom()));
- progressBar->setValue(m_jobList->getJobProgress(current));
- editDetails->setText(m_jobList->data(m_jobList->index(current.row(), 3, QModelIndex()), Qt::DisplayRole).toString());
+ ui->progressBar->setValue(m_jobList->getJobProgress(current));
+ ui->editDetails->setText(m_jobList->data(m_jobList->index(current.row(), 3, QModelIndex()), Qt::DisplayRole).toString());
updateButtons(m_jobList->getJobStatus(current));
updateTaskbar(m_jobList->getJobStatus(current), m_jobList->data(m_jobList->index(current.row(), 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
}
else
{
- logView->setModel(NULL);
- logView->actions().first()->setEnabled(false);
- progressBar->setValue(0);
- editDetails->clear();
+ ui->logView->setModel(NULL);
+ foreach(QAction *action, ui->logView->actions())
+ {
+ action->setEnabled(false);
+ }
+ ui->progressBar->setValue(0);
+ ui->editDetails->clear();
updateButtons(JobStatus_Undefined);
updateTaskbar(JobStatus_Undefined, QIcon());
}
- progressBar->repaint();
+ ui->progressBar->repaint();
}
/*
*/
void MainWindow::jobChangedData(const QModelIndex &topLeft, const QModelIndex &bottomRight)
{
- int selected = jobsView->currentIndex().row();
+ int selected = ui->jobsView->currentIndex().row();
if(topLeft.column() <= 1 && bottomRight.column() >= 1) /*STATUS*/
{
}
if((status == JobStatus_Completed) || (status == JobStatus_Failed))
{
- if(m_preferences->autoRunNextJob()) QTimer::singleShot(0, this, SLOT(launchNextJob()));
- if(m_preferences->shutdownComputer()) QTimer::singleShot(0, this, SLOT(shutdownComputer()));
- if(m_preferences->saveLogFiles()) saveLogFile(m_jobList->index(i, 1, QModelIndex()));
+ if(m_preferences->getAutoRunNextJob()) QTimer::singleShot(0, this, SLOT(launchNextJob()));
+ if(m_preferences->getSaveLogFiles()) saveLogFile(m_jobList->index(i, 1, QModelIndex()));
}
}
}
{
if(i == selected)
{
- progressBar->setValue(m_jobList->getJobProgress(m_jobList->index(i, 0, QModelIndex())));
- WinSevenTaskbar::setTaskbarProgress(this, progressBar->value(), progressBar->maximum());
+ ui->progressBar->setValue(m_jobList->getJobProgress(m_jobList->index(i, 0, QModelIndex())));
+ if(!m_taskbar.isNull())
+ {
+ m_taskbar->setTaskbarProgress(ui->progressBar->value(), ui->progressBar->maximum());
+ }
break;
}
}
{
if(i == selected)
{
- editDetails->setText(m_jobList->data(m_jobList->index(i, 3, QModelIndex()), Qt::DisplayRole).toString());
+ ui->editDetails->setText(m_jobList->data(m_jobList->index(i, 3, QModelIndex()), Qt::DisplayRole).toString());
break;
}
}
*/
void MainWindow::jobLogExtended(const QModelIndex & parent, int start, int end)
{
- QTimer::singleShot(0, logView, SLOT(scrollToBottom()));
+ QTimer::singleShot(0, ui->logView, SLOT(scrollToBottom()));
}
/*
*/
void MainWindow::showAbout(void)
{
- QString text;
-
- text += QString().sprintf("<nobr><tt>Simple x264 Launcher v%u.%02u.%u - use 64-Bit x264 with 32-Bit Avisynth<br>", x264_version_major(), x264_version_minor(), x264_version_build());
- text += QString().sprintf("Copyright (c) 2004-%04d LoRd_MuldeR <mulder2@gmx.de>. Some rights reserved.<br>", qMax(x264_version_date().year(),QDate::currentDate().year()));
- text += QString().sprintf("Built on %s at %s with %s for Win-%s.<br><br>", x264_version_date().toString(Qt::ISODate).toLatin1().constData(), x264_version_time(), x264_version_compiler(), x264_version_arch());
- text += QString().sprintf("This program is free software: you can redistribute it and/or modify<br>");
- text += QString().sprintf("it under the terms of the GNU General Public License <http://www.gnu.org/>.<br>");
- text += QString().sprintf("Note that this program is distributed with ABSOLUTELY NO WARRANTY.<br><br>");
- text += QString().sprintf("Please check the web-site at <a href=\"%s\">%s</a> for updates !!!<br></tt></nobr>", home_url, home_url);
-
- QMessageBox aboutBox(this);
- aboutBox.setIconPixmap(QIcon(":/images/movie.png").pixmap(64,64));
- aboutBox.setWindowTitle(tr("About..."));
- aboutBox.setText(text.replace("-", "−"));
- aboutBox.addButton(tr("About x264"), QMessageBox::NoRole);
- aboutBox.addButton(tr("About AVS"), QMessageBox::NoRole);
- aboutBox.addButton(tr("About Qt"), QMessageBox::NoRole);
- aboutBox.setEscapeButton(aboutBox.addButton(tr("Close"), QMessageBox::NoRole));
-
- forever
+ ENSURE_APP_IS_READY();
+
+ if(AboutDialog *aboutDialog = new AboutDialog(this))
{
- MessageBeep(MB_ICONINFORMATION);
- switch(aboutBox.exec())
- {
- case 0:
- {
- QString text2;
- text2 += tr("<nobr><tt>x264 - the best H.264/AVC encoder. Copyright (c) 2003-2013 x264 project.<br>");
- text2 += tr("Free software library for encoding video streams into the H.264/MPEG-4 AVC format.<br>");
- text2 += tr("Released under the terms of the GNU General Public License.<br><br>");
- text2 += tr("Please visit <a href=\"%1\">%1</a> for obtaining a commercial x264 license.<br>").arg("http://x264licensing.com/");
- text2 += tr("Read the <a href=\"%1\">user's manual</a> to get started and use the <a href=\"%2\">support forum</a> for help!<br></tt></nobr>").arg("http://mewiki.project357.com/wiki/X264_Settings", "http://forum.doom9.org/forumdisplay.php?f=77");
-
- QMessageBox x264Box(this);
- x264Box.setIconPixmap(QIcon(":/images/x264.png").pixmap(48,48));
- x264Box.setWindowTitle(tr("About x264"));
- x264Box.setText(text2.replace("-", "−"));
- x264Box.setEscapeButton(x264Box.addButton(tr("Close"), QMessageBox::NoRole));
- MessageBeep(MB_ICONINFORMATION);
- x264Box.exec();
- }
- break;
- case 1:
- {
- QString text2;
- text2 += tr("<nobr><tt>Avisynth - powerful video processing scripting language.<br>");
- text2 += tr("Copyright (c) 2000 Ben Rudiak-Gould and all subsequent developers.<br>");
- text2 += tr("Released under the terms of the GNU General Public License.<br><br>");
- text2 += tr("Please visit the web-site <a href=\"%1\">%1</a> for more information.<br>").arg("http://avisynth.org/");
- text2 += tr("Read the <a href=\"%1\">guide</a> to get started and use the <a href=\"%2\">support forum</a> for help!<br></tt></nobr>").arg("http://avisynth.org/mediawiki/First_script", "http://forum.doom9.org/forumdisplay.php?f=33");
-
- QMessageBox x264Box(this);
- x264Box.setIconPixmap(QIcon(":/images/avisynth.png").pixmap(48,67));
- x264Box.setWindowTitle(tr("About Avisynth"));
- x264Box.setText(text2.replace("-", "−"));
- x264Box.setEscapeButton(x264Box.addButton(tr("Close"), QMessageBox::NoRole));
- MessageBeep(MB_ICONINFORMATION);
- x264Box.exec();
- }
- break;
- case 2:
- QMessageBox::aboutQt(this);
- break;
- default:
- return;
- }
+ aboutDialog->exec();
+ MUTILS_DELETE(aboutDialog);
}
}
*/
void MainWindow::showWebLink(void)
{
- if(QObject::sender() == actionWebMulder) QDesktopServices::openUrl(QUrl(home_url));
- if(QObject::sender() == actionWebX264) QDesktopServices::openUrl(QUrl("http://www.x264.com/"));
- if(QObject::sender() == actionWebKomisar) QDesktopServices::openUrl(QUrl("http://komisar.gin.by/"));
- if(QObject::sender() == actionWebJarod) QDesktopServices::openUrl(QUrl("http://www.x264.nl/"));
- if(QObject::sender() == actionWebJEEB) QDesktopServices::openUrl(QUrl("http://x264.fushizen.eu/"));
- if(QObject::sender() == actionWebAvisynth32) QDesktopServices::openUrl(QUrl("http://sourceforge.net/projects/avisynth2/files/AviSynth%202.5/"));
- if(QObject::sender() == actionWebAvisynth64) QDesktopServices::openUrl(QUrl("http://code.google.com/p/avisynth64/downloads/list"));
- if(QObject::sender() == actionWebWiki) QDesktopServices::openUrl(QUrl("http://mewiki.project357.com/wiki/X264_Settings"));
- if(QObject::sender() == actionWebBluRay) QDesktopServices::openUrl(QUrl("http://www.x264bluray.com/"));
- if(QObject::sender() == actionWebAvsWiki) QDesktopServices::openUrl(QUrl("http://avisynth.org/mediawiki/Main_Page#Usage"));
- if(QObject::sender() == actionWebSupport) QDesktopServices::openUrl(QUrl("http://forum.doom9.org/showthread.php?t=144140"));
- if(QObject::sender() == actionWebSecret) QDesktopServices::openUrl(QUrl("http://www.youtube.com/watch_popup?v=AXIeHY-OYNI"));
+ ENSURE_APP_IS_READY();
+
+ if(QObject *obj = QObject::sender())
+ {
+ if(QAction *action = dynamic_cast<QAction*>(obj))
+ {
+ if(action->data().type() == QVariant::Url)
+ {
+ QDesktopServices::openUrl(action->data().toUrl());
+ }
+ }
+ }
}
/*
*/
void MainWindow::showPreferences(void)
{
- PreferencesDialog *preferences = new PreferencesDialog(this, m_preferences, m_cpuFeatures->x64);
+ ENSURE_APP_IS_READY();
+
+ PreferencesDialog *preferences = new PreferencesDialog(this, m_preferences.data(), m_sysinfo.data());
preferences->exec();
- X264_DELETE(preferences);
+
+ MUTILS_DELETE(preferences);
}
/*
*/
void MainWindow::launchNextJob(void)
{
- qDebug("launchNextJob(void)");
-
- const int rows = m_jobList->rowCount(QModelIndex());
+ qDebug("Launching next job...");
- if(countRunningJobs() >= m_preferences->maxRunningJobCount())
+ if(countRunningJobs() >= m_preferences->getMaxRunningJobCount())
{
qDebug("Still have too many jobs running, won't launch next one yet!");
return;
}
- int startIdx= jobsView->currentIndex().isValid() ? qBound(0, jobsView->currentIndex().row(), rows-1) : 0;
+ const int rows = m_jobList->rowCount(QModelIndex());
for(int i = 0; i < rows; i++)
{
- int currentIdx = (i + startIdx) % rows;
- JobStatus status = m_jobList->getJobStatus(m_jobList->index(currentIdx, 0, QModelIndex()));
- if(status == JobStatus_Enqueued)
+ const QModelIndex currentIndex = m_jobList->index(i, 0, QModelIndex());
+ if(m_jobList->getJobStatus(currentIndex) == JobStatus_Enqueued)
{
- if(m_jobList->startJob(m_jobList->index(currentIdx, 0, QModelIndex())))
+ if(m_jobList->startJob(currentIndex))
{
- jobsView->selectRow(currentIdx);
+ ui->jobsView->selectRow(currentIndex.row());
return;
}
}
}
- qWarning("No enqueued jobs left!");
+ qWarning("No enqueued jobs left to be started!");
+
+ if(m_postOperation)
+ {
+ qDebug("Post operation has been scheduled! (m_postOperation: %d)", m_postOperation);
+ QTimer::singleShot(0, this, SLOT(shutdownComputer()));
+ }
}
/*
{
if(index.isValid())
{
- if(LogFileModel *log = m_jobList->getLogFile(index))
+ const LogFileModel *const logData = m_jobList->getLogFile(index);
+ const QString &outputFilePath = m_jobList->getJobOutputFile(index);
+ if(logData && (!outputFilePath.isEmpty()))
{
- QDir(QString("%1/logs").arg(x264_data_path())).mkpath(".");
- QString logFilePath = QString("%1/logs/LOG.%2.%3.txt").arg(x264_data_path(), QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString(Qt::ISODate).replace(':', "-"));
- QFile outFile(logFilePath);
- if(outFile.open(QIODevice::WriteOnly))
+ const QFileInfo outputFileInfo(outputFilePath);
+ if (outputFileInfo.absoluteDir().exists())
{
- QTextStream outStream(&outFile);
- outStream.setCodec("UTF-8");
- outStream.setGenerateByteOrderMark(true);
-
- const int rows = log->rowCount(QModelIndex());
- for(int i = 0; i < rows; i++)
+ const QString outputDir = outputFileInfo.absolutePath(), outputName = outputFileInfo.fileName();
+ const QString logFilePath = MUtils::make_unique_file(outputDir, outputName, QLatin1String("log"), true);
+ if (!logFilePath.isEmpty())
{
- outStream << log->data(log->index(i, 0, QModelIndex()), Qt::DisplayRole).toString() << QLatin1String("\r\n");
+ qDebug("Saving log file to: \"%s\"", MUTILS_UTF8(logFilePath));
+ if (!logData->saveToLocalFile(logFilePath))
+ {
+ qWarning("Failed to open log file for writing:\n%s", logFilePath.toUtf8().constData());
+ }
+ }
+ else
+ {
+ qWarning("Failed to generate log file name. Giving up!");
}
- outFile.close();
}
else
{
- qWarning("Failed to open log file for writing:\n%s", logFilePath.toUtf8().constData());
+ qWarning("Output directory does not seem to exist. Giving up!");
}
}
}
*/
void MainWindow::shutdownComputer(void)
{
- qDebug("shutdownComputer(void)");
-
+ ENSURE_APP_IS_READY();
+ qDebug("shutdownComputer (m_postOperation: %d)", m_postOperation);
+
if(countPendingJobs() > 0)
{
- qDebug("Still have pending jobs, won't shutdown yet!");
+ qWarning("Still have pending jobs, won't shutdown yet!");
return;
}
-
+
+ if ((m_postOperation != POST_OP_POWERDOWN) && (m_postOperation != POST_OP_HIBERNATE))
+ {
+ qWarning("No post-operation has been schedule!");
+ }
+
const int iTimeout = 30;
const Qt::WindowFlags flags = Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowSystemMenuHint;
- const QString text = QString("%1%2%1").arg(QString().fill(' ', 18), tr("Warning: Computer will shutdown in %1 seconds..."));
+ const bool hibernate = (m_postOperation == POST_OP_HIBERNATE);
+ const QString text = QString("%1%2%1").arg(QString().fill(' ', 18), hibernate ? tr("Warning: Computer will hibernate in %1 seconds...") : tr("Warning: Computer will shutdown in %1 seconds..."));
qWarning("Initiating shutdown sequence!");
QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
QApplication::setOverrideCursor(Qt::WaitCursor);
- PlaySound(MAKEINTRESOURCE(IDR_WAVE1), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
+ MUtils::Sound::play_sound("shutdown", false);
QApplication::restoreOverrideCursor();
QTimer timer;
progressDialog.setLabelText(text.arg(iTimeout-i));
if(iTimeout-i == 3) progressDialog.setCancelButton(NULL);
QApplication::processEvents();
- PlaySound(MAKEINTRESOURCE((i < iTimeout) ? IDR_WAVE2 : IDR_WAVE3), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
+ MUtils::Sound::play_sound(((i < iTimeout) ? "beep" : "beep2"), false);
}
qWarning("Shutting down !!!");
- if(x264_shutdown_computer("Simple x264 Launcher: All jobs completed, shutting down!", 10, true))
+ if(MUtils::OS::shutdown_computer("Simple x264 Launcher: All jobs completed, shutting down!", 10, true, hibernate))
{
qApp->closeAllWindows();
}
+
}
/*
*/
void MainWindow::init(void)
{
- static const char *binFiles = "x86/x264_8bit_x86.exe:x64/x264_8bit_x64.exe:x86/x264_10bit_x86.exe:x64/x264_10bit_x64.exe:x86/avs2yuv_x86.exe:x64/avs2yuv_x64.exe";
- QStringList binaries = QString::fromLatin1(binFiles).split(":", QString::SkipEmptyParts);
-
- updateLabelPos();
-
- //Check for a running instance
- bool firstInstance = false;
- if(m_ipcThread->initialize(&firstInstance))
+ if(m_initialized)
{
- m_ipcThread->start();
- if(!firstInstance)
- {
- if(!m_ipcThread->wait(5000))
- {
- QMessageBox::warning(this, tr("Not Responding"), tr("<nobr>Another instance of this application is already running, but did not respond in time.<br>If the problem persists, please kill the running instance from the task manager!</nobr>"), tr("Quit"));
- m_ipcThread->terminate();
- m_ipcThread->wait();
- }
- close(); qApp->exit(-1); return;
- }
+ qWarning("Already initialized -> skipping!");
+ return;
}
- //Check all binaries
- while(!binaries.isEmpty())
+ updateLabelPos();
+ const MUtils::OS::ArgumentMap &arguments = MUtils::OS::arguments();
+ qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
+
+ //---------------------------------------
+ // Check required binaries
+ //---------------------------------------
+
+ qDebug("[Validating binaries]");
+ QString failedPath;
+ if(!BinariesCheckThread::check(m_sysinfo.data(), &failedPath))
{
- qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
- QString current = binaries.takeFirst();
- QFile *file = new QFile(QString("%1/toolset/%2").arg(m_appDir, current));
- if(file->open(QIODevice::ReadOnly))
- {
- bool binaryTypeOkay = false;
- DWORD binaryType;
- if(GetBinaryType(QWCHAR(QDir::toNativeSeparators(file->fileName())), &binaryType))
- {
- binaryTypeOkay = (binaryType == SCS_32BIT_BINARY || binaryType == SCS_64BIT_BINARY);
- }
- if(!binaryTypeOkay)
- {
- QMessageBox::critical(this, tr("Invalid File!"), tr("<nobr>At least on required tool is not a valid Win32 or Win64 binary:<br><tt style=\"whitespace:nowrap\">%1</tt><br><br>Please re-install the program in order to fix the problem!</nobr>").arg(QDir::toNativeSeparators(QString("%1/toolset/%2").arg(m_appDir, current))).replace("-", "−"));
- qFatal(QString("Binary is invalid: %1/toolset/%2").arg(m_appDir, current).toLatin1().constData());
- close(); qApp->exit(-1); return;
- }
- m_toolsList << file;
- }
- else
- {
- X264_DELETE(file);
- QMessageBox::critical(this, tr("File Not Found!"), tr("<nobr>At least on required tool could not be found:<br><tt style=\"whitespace:nowrap\">%1</tt><br><br>Please re-install the program in order to fix the problem!</nobr>").arg(QDir::toNativeSeparators(QString("%1/toolset/%2").arg(m_appDir, current))).replace("-", "−"));
- qFatal(QString("Binary not found: %1/toolset/%2").arg(m_appDir, current).toLatin1().constData());
- close(); qApp->exit(-1); return;
- }
+ QMessageBox::critical(this, tr("Invalid File!"), tr("<nobr>At least one tool is missing or is not a valid Win32/Win64 binary:</nobr><br><tt>%1</tt><br><br><nobr>Please re-install the program in order to fix the problem!</nobr>").replace("-", "−").arg(Qt::escape(QDir::toNativeSeparators(failedPath))));
+ qFatal("At least one tool is missing or is not a valid Win32/Win64 binary. Program will exit now!");
}
+ qDebug(" ");
+
+ //---------------------------------------
+ // Check for portable mode
+ //---------------------------------------
- //Check for portable mode
- if(x264_portable())
+ if(x264_is_portable())
{
bool ok = false;
static const char *data = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
if(!ok)
{
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"));
- if(val != 1) { close(); qApp->exit(-1); return; }
+ if(val != 1) INIT_ERROR_EXIT();
}
}
{
qsrand(time(NULL)); int rnd = qrand() % 3;
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);
- if(rnd != val) { close(); qApp->exit(-1); return; }
+ if(rnd != val) INIT_ERROR_EXIT();
}
+ qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
+
+ //---------------------------------------
+ // Check CPU capabilities
+ //---------------------------------------
+
//Make sure this CPU can run x264 (requires MMX + MMXEXT/iSSE to run x264 with ASM enabled, additionally requires SSE1 for most x264 builds)
- if(!(m_cpuFeatures->mmx && m_cpuFeatures->mmx2))
+ if(!m_sysinfo->getCPUFeatures(SysinfoModel::CPUFeatures_MMX))
{
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"));
qFatal("System does not support MMX and MMXEXT, x264 will not work !!!");
- close(); qApp->exit(-1); return;
+ INIT_ERROR_EXIT();
}
- else if(!(m_cpuFeatures->mmx && m_cpuFeatures->sse))
+ else if(!m_sysinfo->getCPUFeatures(SysinfoModel::CPUFeatures_SSE))
{
- qWarning("WARNING: System does not support SSE1, most x264 builds will not work !!!\n");
- int val = QMessageBox::warning(this, tr("Unsupported CPU"), tr("<nobr>It appears that this machine does <b>not</b> support the SSE1 instruction set.<br>Thus most builds of x264 will <b>not</b> run on this computer at all.<br><br>Please get a CPU that supports the MMX and SSE1 instruction sets!</nobr>"), tr("Quit"), tr("Ignore"));
- if(val != 1) { close(); qApp->exit(-1); return; }
+ qWarning("WARNING: System does not support SSE (v1), x264/x265 probably will *not* work !!!\n");
+ 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"));
+ if(val != 1) INIT_ERROR_EXIT();
}
//Skip version check (not recommended!)
- if(qApp->arguments().contains("--skip-x264-version-check", Qt::CaseInsensitive))
+ if(arguments.contains(CLI_PARAM_SKIP_VERSION_CHECK))
{
- qWarning("x264 version check disabled, you have been warned!\n");
- m_skipVersionTest = true;
+ qWarning("Version checks are disabled now, you have been warned!\n");
+ m_preferences->setSkipVersionTest(true);
}
//Don't abort encoding process on timeout (not recommended!)
- if(qApp->arguments().contains("--no-deadlock-detection", Qt::CaseInsensitive))
+ if(arguments.contains(CLI_PARAM_NO_DEADLOCK))
{
qWarning("Deadlock detection disabled, you have been warned!\n");
- m_abortOnTimeout = false;
+ m_preferences->setAbortOnTimeout(false);
}
- //Check for Avisynth support
- if(!qApp->arguments().contains("--skip-avisynth-check", Qt::CaseInsensitive))
+ qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
+
+ //---------------------------------------
+ // Check Avisynth support
+ //---------------------------------------
+
+ if(!arguments.contains(CLI_PARAM_SKIP_AVS_CHECK))
{
qDebug("[Check for Avisynth support]");
- volatile double avisynthVersion = 0.0;
- const int result = AvisynthCheckThread::detect(&avisynthVersion);
- if(result < 0)
+ if(!AvisynthCheckThread::detect(m_sysinfo.data()))
{
QString text = tr("A critical error was encountered while checking your Avisynth version.").append("<br>");
text += tr("This is most likely caused by an erroneous Avisynth Plugin, please try to clean your Plugins folder!").append("<br>");
text += tr("We suggest to move all .dll and .avsi files out of your Avisynth Plugins folder and try again.");
int val = QMessageBox::critical(this, tr("Avisynth Error"), QString("<nobr>%1</nobr>").arg(text).replace("-", "−"), tr("Quit"), tr("Ignore"));
- if(val != 1) { close(); qApp->exit(-1); return; }
+ if(val != 1) INIT_ERROR_EXIT();
}
- if((!result) || (avisynthVersion < 2.5))
+ else if((!m_sysinfo->hasAvisynth()) && (!m_preferences->getDisableWarnings()))
{
- int val = QMessageBox::warning(this, tr("Avisynth Missing"), tr("<nobr>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!<br><br>Please download and install Avisynth:<br><a href=\"http://sourceforge.net/projects/avisynth2/files/AviSynth%202.5/\">http://sourceforge.net/projects/avisynth2/files/AviSynth 2.5/</a></nobr>").replace("-", "−"), tr("Quit"), tr("Ignore"));
- if(val != 1) { close(); qApp->exit(-1); return; }
+ 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>");
+ text += tr("Please download and install Avisynth:").append("<br>").append(LINK(avs_dl_url));
+ int val = QMessageBox::warning(this, tr("Avisynth Missing"), QString("<nobr>%1</nobr>").arg(text).replace("-", "−"), tr("Close"), tr("Disable this Warning"));
+ if(val == 1)
+ {
+ m_preferences->setDisableWarnings(true);
+ PreferencesModel::savePreferences(m_preferences.data());
+ }
}
- qDebug("");
+ qDebug(" ");
}
- //Check for Vapoursynth support
- if(!qApp->arguments().contains("--skip-vapoursynth-check", Qt::CaseInsensitive))
+ //---------------------------------------
+ // Check VapurSynth support
+ //---------------------------------------
+
+ if(!arguments.contains(CLI_PARAM_SKIP_VPS_CHECK))
{
qDebug("[Check for VapourSynth support]");
- const QString vapursynthPath = getVapoursynthLocation();
- if(!vapursynthPath.isEmpty())
+ if(!VapourSynthCheckThread::detect(m_sysinfo.data()))
{
- QFile *vpsExePath = new QFile(QString("%1/core/vspipe.exe").arg(vapursynthPath));
- QFile *vpsDllPath = new QFile(QString("%1/core/vapoursynth.dll").arg(vapursynthPath));
- qDebug("VapourSynth EXE: %s", vpsExePath->fileName().toUtf8().constData());
- qDebug("VapourSynth DLL: %s", vpsDllPath->fileName().toUtf8().constData());
- if(checkVapourSynth(vpsExePath, vpsDllPath))
- {
- qDebug("VapourSynth support enabled.");
- m_vapoursynthPath = QFileInfo(vpsExePath->fileName()).canonicalPath();
- m_toolsList << vpsExePath;
- m_toolsList << vpsDllPath;
- }
- else
+ QString text = tr("A critical error was encountered while checking your VapourSynth installation.").append("<br>");
+ text += tr("This is most likely caused by an erroneous VapourSynth Plugin, please try to clean your Filters folder!").append("<br>");
+ text += tr("We suggest to move all .dll files out of your VapourSynth Filters folder and try again.");
+ const int val = QMessageBox::critical(this, tr("VapourSynth Error"), QString("<nobr>%1</nobr>").arg(text).replace("-", "−"), tr("Quit"), tr("Ignore"));
+ if(val != 1) INIT_ERROR_EXIT();
+ }
+ else if((!m_sysinfo->hasVapourSynth()) && (!m_preferences->getDisableWarnings()))
+ {
+ 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>");
+ 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>");
+ text += tr("Note that Python v3.4 is a prerequisite for installing VapourSynth:").append("<br>").append(LINK(python_url)).append("<br>");
+ const int val = QMessageBox::warning(this, tr("VapourSynth Missing"), QString("<nobr>%1</nobr>").arg(text).replace("-", "−"), tr("Close"), tr("Disable this Warning"));
+ if(val == 1)
{
- qDebug("VapourSynth not avilable -> disable Vapousynth support!");
- X264_DELETE(vpsExePath);
- X264_DELETE(vpsDllPath);
- int val = QMessageBox::warning(this, tr("VapourSynth Missing"), tr("<nobr>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!<br><br>Please download and install VapourSynth (r19 or later) here:<br><a href=\"http://www.vapoursynth.com/\">http://www.vapoursynth.com/</a></nobr>").replace("-", "−"), tr("Quit"), tr("Ignore"));
- if(val != 1) { close(); qApp->exit(-1); return; }
+ m_preferences->setDisableWarnings(true);
+ PreferencesModel::savePreferences(m_preferences.data());
}
}
- qDebug("");
+ qDebug(" ");
+ }
+
+ //---------------------------------------
+ // Create the IPC listener thread
+ //---------------------------------------
+
+ if(m_ipcChannel)
+ {
+ m_ipcThread.reset(new IPCThread_Recv(m_ipcChannel));
+ connect(m_ipcThread.data(), SIGNAL(receivedCommand(int,QStringList,quint32)), this, SLOT(handleCommand(int,QStringList,quint32)), Qt::QueuedConnection);
+ m_ipcThread->start();
+ }
+
+ //---------------------------------------
+ // Finish initialization
+ //---------------------------------------
+
+ //Set Window title
+ setWindowTitle(QString("%1 (%2)").arg(windowTitle(), m_sysinfo->getCPUFeatures(SysinfoModel::CPUFeatures_X64) ? "64-Bit" : "32-Bit"));
+
+ //Enable drag&drop support for this window, required for Qt v4.8.4+
+ setAcceptDrops(true);
+
+ //Update flag
+ m_initialized = true;
+
+ //Hide the spinner animation
+ if(!m_label[1].isNull())
+ {
+ if(!m_animation.isNull())
+ {
+ m_animation->stop();
+ }
+ m_label[1]->setVisible(false);
}
- //Check for expiration
- if(x264_version_date().addMonths(6) < QDate::currentDate())
+ //---------------------------------------
+ // Check for Expiration
+ //---------------------------------------
+
+ if(MUtils::Version::app_build_date().addMonths(6) < MUtils::OS::current_date())
{
+ if(QWidget *cornerWidget = ui->menubar->cornerWidget()) cornerWidget->show();
+ QString text;
+ text += QString("<nobr><tt>%1</tt></nobr><br><br>").arg(tr("Your version of Simple x264 Launcher is more than 6 months old!").replace('-', "−"));
+ 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("-", "−"));
+ text += QString("<nobr><tt>%1</tt></nobr><br>").arg(tr("Alternatively, click 'Check for Updates' to run the auto-update utility.").replace('-', "−"));
QMessageBox msgBox(this);
msgBox.setIconPixmap(QIcon(":/images/update.png").pixmap(56,56));
msgBox.setWindowTitle(tr("Update Notification"));
msgBox.setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
- msgBox.setText(tr("<nobr><tt>Your version of 'Simple x264 Launcher' is more than 6 months old!<br><br>Please download the most recent version from the official web-site at:<br><a href=\"%1\">%1</a><br></tt></nobr>").replace("-", "−").arg(update_url));
- QPushButton *btn1 = msgBox.addButton(tr("Discard"), QMessageBox::NoRole);
- QPushButton *btn2 = msgBox.addButton(tr("Discard"), QMessageBox::AcceptRole);
- btn1->setEnabled(false);
- btn2->setVisible(false);
- QTimer::singleShot(5000, btn1, SLOT(hide()));
- QTimer::singleShot(5000, btn2, SLOT(show()));
- msgBox.exec();
- }
-
- //Add files from command-line
- bool bAddFile = false;
- QStringList files, args = qApp->arguments();
- while(!args.isEmpty())
- {
- QString current = args.takeFirst();
- if(!bAddFile)
+ msgBox.setText(text);
+ QPushButton *btn1 = msgBox.addButton(tr("Check for Updates"), QMessageBox::AcceptRole);
+ QPushButton *btn2 = msgBox.addButton(tr("Discard"), QMessageBox::NoRole);
+ QPushButton *btn3 = msgBox.addButton(btn2->text(), QMessageBox::RejectRole);
+ btn2->setEnabled(false);
+ btn3->setVisible(false);
+ QTimer::singleShot(7500, btn2, SLOT(hide()));
+ QTimer::singleShot(7500, btn3, SLOT(show()));
+ if(msgBox.exec() == 0)
{
- bAddFile = (current.compare("--add", Qt::CaseInsensitive) == 0);
- continue;
+ QTimer::singleShot(0, this, SLOT(checkUpdates()));
+ return;
}
- if((!current.startsWith("--")) && QFileInfo(current).exists() && QFileInfo(current).isFile())
+ }
+ else if(!parseCommandLineArgs())
+ {
+ //Update reminder
+ if(arguments.contains(CLI_PARAM_FIRST_RUN))
{
- files << QFileInfo(current).canonicalFilePath();
+ qWarning("First run -> resetting update check now!");
+ m_recentlyUsed->setLastUpdateCheck(0);
+ RecentlyUsed::saveRecentlyUsed(m_recentlyUsed.data());
+ }
+ else if(m_recentlyUsed->lastUpdateCheck() + 14 < MUtils::OS::current_date().toJulianDay())
+ {
+ if(QWidget *cornerWidget = ui->menubar->cornerWidget()) cornerWidget->show();
+ if(!m_preferences->getNoUpdateReminder())
+ {
+ 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)
+ {
+ QTimer::singleShot(0, this, SLOT(checkUpdates()));
+ return;
+ }
+ }
}
}
- if(files.count() > 0)
+
+ //Load queued jobs
+ if(m_jobList->loadQueuedJobs(m_sysinfo.data()) > 0)
{
- createJobMultiple(files);
+ m_label[0]->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
+ m_jobList->clearQueuedJobs();
}
-
- //Enable drag&drop support for this window, required for Qt v4.8.4+
- setAcceptDrops(true);
}
/*
*/
void MainWindow::updateLabelPos(void)
{
- const QWidget *const viewPort = jobsView->viewport();
- m_label->setGeometry(0, 0, viewPort->width(), viewPort->height());
+ for(int i = 0; i < 2; i++)
+ {
+ //const QWidget *const viewPort = ui->jobsView->viewport();
+ const QWidget *const viewPort = dynamic_cast<QWidget*>(m_label[i]->parent());
+ if(viewPort)
+ {
+ m_label[i]->setGeometry(0, 0, viewPort->width(), viewPort->height());
+ }
+ }
}
/*
*/
void MainWindow::copyLogToClipboard(bool checked)
{
- qDebug("copyLogToClipboard");
+ qDebug("Coyping logfile to clipboard...");
- if(LogFileModel *log = dynamic_cast<LogFileModel*>(logView->model()))
+ if(LogFileModel *log = dynamic_cast<LogFileModel*>(ui->logView->model()))
{
log->copyToClipboard();
- MessageBeep(MB_ICONINFORMATION);
+ MUtils::Sound::beep(MUtils::Sound::BEEP_NFO);
}
}
/*
+ * Save log to local file
+ */
+void MainWindow::saveLogToLocalFile(bool checked)
+{
+ ENSURE_APP_IS_READY();
+
+ const QModelIndex index = ui->jobsView->currentIndex();
+ const QString initialName = index.isValid() ? QFileInfo(m_jobList->getJobOutputFile(index)).completeBaseName() : tr("Logfile");
+ const QString fileName = QFileDialog::getSaveFileName(this, tr("Save Log File"), initialName, tr("Log File (*.log)"));
+ if(!fileName.isEmpty())
+ {
+ if(LogFileModel *log = dynamic_cast<LogFileModel*>(ui->logView->model()))
+ {
+ if(!log->saveToLocalFile(fileName))
+ {
+ QMessageBox::warning(this, this->windowTitle(), tr("Error: Log file could not be saved!"));
+ }
+ }
+ }
+}
+
+/*
+ * Toggle line-wrapping
+ */
+void MainWindow::toggleLineWrapping(bool checked)
+{
+ ui->logView->setWordWrap(checked);
+}
+
+/*
* Process the dropped files
*/
-void MainWindow::handleDroppedFiles(void)
+void MainWindow::handlePendingFiles(void)
{
- qDebug("MainWindow::handleDroppedFiles");
- if(m_droppedFiles)
+ qDebug("MainWindow::handlePendingFiles");
+
+ if(!m_pendingFiles->isEmpty())
{
- QStringList droppedFiles(*m_droppedFiles);
- m_droppedFiles->clear();
- createJobMultiple(droppedFiles);
+ QStringList pendingFiles(*m_pendingFiles);
+ m_pendingFiles->clear();
+ createJobMultiple(pendingFiles);
}
- qDebug("Leave from MainWindow::handleDroppedFiles!");
+
+ qDebug("Leave from MainWindow::handlePendingFiles!");
}
-void MainWindow::instanceCreated(DWORD pid)
+/*
+ * Handle incoming IPC command
+ */
+void MainWindow::handleCommand(const int &command, const QStringList &args, const quint32 &flags)
{
- qDebug("Notification from other instance (PID=0x%X) received!", pid);
+ if(!(m_initialized && (QApplication::activeModalWidget() == NULL)))
+ {
+ qWarning("Cannot accapt commands at this time -> discarding!");
+ return;
+ }
- FLASHWINFO flashWinInfo;
- memset(&flashWinInfo, 0, sizeof(FLASHWINFO));
- flashWinInfo.cbSize = sizeof(FLASHWINFO);
- flashWinInfo.hwnd = this->winId();
- flashWinInfo.dwFlags = FLASHW_ALL;
- flashWinInfo.dwTimeout = 125;
- flashWinInfo.uCount = 5;
-
- SwitchToThisWindow(this->winId(), TRUE);
- SetForegroundWindow(this->winId());
- qApp->processEvents();
- FlashWindowEx(&flashWinInfo);
+ if((!isVisible()) || m_sysTray->isVisible())
+ {
+ sysTrayActived();
+ }
+
+ MUtils::GUI::bring_to_front(this);
+
+#ifdef IPC_LOGGING
+ qDebug("\n---------- IPC ----------");
+ qDebug("CommandId: %d", command);
+ for(QStringList::ConstIterator iter = args.constBegin(); iter != args.constEnd(); iter++)
+ {
+ qDebug("Arguments: %s", iter->toUtf8().constData());
+ }
+ qDebug("The Flags: 0x%08X", flags);
+ qDebug("---------- IPC ----------\n");
+#endif //IPC_LOGGING
+
+ switch(command)
+ {
+ case IPC_OPCODE_PING:
+ qDebug("Received a PING request from another instance!");
+ MUtils::GUI::blink_window(this, 5, 125);
+ break;
+ case IPC_OPCODE_ADD_FILE:
+ if(!args.isEmpty())
+ {
+ if(QFileInfo(args[0]).exists() && QFileInfo(args[0]).isFile())
+ {
+ *m_pendingFiles << QFileInfo(args[0]).canonicalFilePath();
+ if(!m_fileTimer->isActive())
+ {
+ m_fileTimer->setSingleShot(true);
+ m_fileTimer->start(5000);
+ }
+ }
+ else
+ {
+ qWarning("File '%s' not found!", args[0].toUtf8().constData());
+ }
+ }
+ break;
+ case IPC_OPCODE_ADD_JOB:
+ if(args.size() >= 3)
+ {
+ if(QFileInfo(args[0]).exists() && QFileInfo(args[0]).isFile())
+ {
+ OptionsModel options(m_sysinfo.data());
+ bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
+ if(!(args[2].isEmpty() || X264_STRCMP(args[2], "-")))
+ {
+ if(!OptionsModel::loadTemplate(&options, args[2].trimmed()))
+ {
+ qWarning("Template '%s' could not be found -> using defaults!", args[2].trimmed().toUtf8().constData());
+ }
+ }
+ if((flags & IPC_FLAG_FORCE_START) && (!(flags & IPC_FLAG_FORCE_ENQUEUE))) runImmediately = true;
+ if((flags & IPC_FLAG_FORCE_ENQUEUE) && (!(flags & IPC_FLAG_FORCE_START))) runImmediately = false;
+ appendJob(args[0], args[1], &options, runImmediately);
+ }
+ else
+ {
+ qWarning("Source file '%s' not found!", args[0].toUtf8().constData());
+ }
+ }
+ break;
+ default:
+ MUTILS_THROW("Unknown command received!");
+ }
+}
+
+/*
+ * Check for new updates
+ */
+void MainWindow::checkUpdates(void)
+{
+ ENSURE_APP_IS_READY();
+
+ if(countRunningJobs() > 0)
+ {
+ QMessageBox::warning(this, tr("Jobs Are Running"), tr("Sorry, can not update while there still are running jobs!"));
+ return;
+ }
+
+ UpdaterDialog *updater = new UpdaterDialog(this, m_sysinfo.data(), update_url);
+ const int ret = updater->exec();
+
+ if(updater->getSuccess())
+ {
+ m_recentlyUsed->setLastUpdateCheck(MUtils::OS::current_date().toJulianDay());
+ RecentlyUsed::saveRecentlyUsed(m_recentlyUsed.data());
+ if(QWidget *cornerWidget = ui->menubar->cornerWidget()) cornerWidget->hide();
+ }
+
+ if(ret == UpdaterDialog::READY_TO_INSTALL_UPDATE)
+ {
+ qWarning("Exitting program to install update...");
+ close();
+ QApplication::quit();
+ }
+
+ MUTILS_DELETE(updater);
+}
+
+/*
+ * Handle mouse event for version label
+ */
+void MainWindow::versionLabelMouseClicked(const int &tag)
+{
+ if(tag == 0)
+ {
+ QTimer::singleShot(0, this, SLOT(showAbout()));
+ }
+}
+
+/*
+ * Handle key event for job list
+ */
+void MainWindow::jobListKeyPressed(const int &tag)
+{
+ switch(tag)
+ {
+ case 1:
+ ui->actionJob_MoveUp->trigger();
+ break;
+ case 2:
+ ui->actionJob_MoveDown->trigger();
+ break;
+ }
+}
+
+/*
+ * System tray was activated
+ */
+void MainWindow::sysTrayActived(void)
+{
+ m_sysTray->hide();
+ showNormal();
+ MUtils::GUI::bring_to_front(this);
}
///////////////////////////////////////////////////////////////////////////////
{
QMainWindow::showEvent(e);
- if(m_firstShow)
+ if(!m_initialized)
{
- m_firstShow = false;
QTimer::singleShot(0, this, SLOT(init()));
}
}
*/
void MainWindow::closeEvent(QCloseEvent *e)
{
+ if(!APP_IS_READY)
+ {
+ e->ignore();
+ qWarning("Cannot close window at this time!");
+ return;
+ }
+
+ //Make sure we have no running jobs left!
if(countRunningJobs() > 0)
{
e->ignore();
- QMessageBox::warning(this, tr("Jobs Are Running"), tr("Sorry, can not exit while there still are running jobs!"));
+ if(!m_preferences->getNoSystrayWarning())
+ {
+ 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)
+ {
+ m_preferences->setNoSystrayWarning(true);
+ PreferencesModel::savePreferences(m_preferences.data());
+ }
+ }
+ hide();
+ m_sysTray->show();
return;
}
-
+
+ //Save pending jobs for next time, if desired by user
if(countPendingJobs() > 0)
{
- int ret = QMessageBox::question(this, tr("Jobs Are Pending"), tr("Do you really want to quit and discard the pending jobs?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
- if(ret != QMessageBox::Yes)
+ if (!m_preferences->getSaveQueueNoConfirm())
{
- e->ignore();
- return;
+ const int ret = QMessageBox::question(this, tr("Jobs Are Pending"), tr("<nobr>You still have some pending jobs in your queue. How do you want to proceed?</nobr>"), tr("Save Jobs"), tr("Always Save Jobs"), tr("Discard Jobs"));
+ if ((ret >= 0) && (ret <= 1))
+ {
+ if (ret > 0)
+ {
+ m_preferences->setSaveQueueNoConfirm(true);
+ PreferencesModel::savePreferences(m_preferences.data());
+ }
+ m_jobList->saveQueuedJobs();
+ }
+ }
+ else
+ {
+ m_jobList->saveQueuedJobs();
}
}
-
+
+ //Delete remaining jobs
while(m_jobList->rowCount(QModelIndex()) > 0)
{
- qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
+ if((m_jobList->rowCount(QModelIndex()) % 10) == 0)
+ {
+ qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
+ }
if(!m_jobList->deleteJob(m_jobList->index(0, 0, QModelIndex())))
{
e->ignore();
- QMessageBox::warning(this, tr("Failed To Exit"), tr("Sorry, at least one job could not be deleted!"));
- return;
+ QMessageBox::warning(this, tr("Failed To Exit"), tr("Warning: At least one job could not be deleted!"));
}
}
-
+
qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
QMainWindow::closeEvent(e);
}
}
/*
- * Event filter
- */
-bool MainWindow::eventFilter(QObject *o, QEvent *e)
-{
- if((o == labelBuildDate) && (e->type() == QEvent::MouseButtonPress))
- {
- QTimer::singleShot(0, this, SLOT(showAbout()));
- return true;
- }
- return false;
-}
-
-/*
- * Win32 message filter
- */
-bool MainWindow::winEvent(MSG *message, long *result)
-{
- return WinSevenTaskbar::handleWinEvent(message, result);
-}
-
-/*
* File dragged over window
*/
void MainWindow::dragEnterEvent(QDragEnterEvent *event)
*/
void MainWindow::dropEvent(QDropEvent *event)
{
+ if(!(m_initialized && (QApplication::activeModalWidget() == NULL)))
+ {
+ qWarning("Cannot accept dropped files at this time -> discarding!");
+ return;
+ }
+
QStringList droppedFiles;
QList<QUrl> urls = event->mimeData()->urls();
if(droppedFiles.count() > 0)
{
- if(!m_droppedFiles)
+ m_pendingFiles->append(droppedFiles);
+ m_pendingFiles->sort();
+ if(!m_fileTimer->isActive())
{
- m_droppedFiles = new QStringList();
+ m_fileTimer->setSingleShot(true);
+ m_fileTimer->start(5000);
}
- m_droppedFiles->append(droppedFiles);
- m_droppedFiles->sort();
- QTimer::singleShot(0, this, SLOT(handleDroppedFiles()));
}
}
bool MainWindow::createJob(QString &sourceFileName, QString &outputFileName, OptionsModel *options, bool &runImmediately, const bool restart, int fileNo, int fileTotal, bool *applyToAll)
{
bool okay = false;
- AddJobDialog *addDialog = new AddJobDialog(this, options, m_recentlyUsed, m_cpuFeatures->x64, m_preferences->use10BitEncoding(), m_preferences->saveToSourcePath());
+ AddJobDialog *addDialog = new AddJobDialog(this, options, m_recentlyUsed.data(), m_sysinfo.data(), m_preferences.data());
addDialog->setRunImmediately(runImmediately);
if(!sourceFileName.isEmpty()) addDialog->setSourceFile(sourceFileName);
okay = true;
}
- X264_DELETE(addDialog);
+ MUTILS_DELETE(addDialog);
return okay;
}
//Add files individually
for(iter = filePathIn.constBegin(); (iter != filePathIn.constEnd()) && (!applyToAll); iter++)
{
- runImmediately = (countRunningJobs() < (m_preferences->autoRunNextJob() ? m_preferences->maxRunningJobCount() : 1));
+ runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
QString sourceFileName(*iter), outputFileName;
- if(createJob(sourceFileName, outputFileName, m_options, runImmediately, false, counter++, filePathIn.count(), &applyToAll))
+ if(createJob(sourceFileName, outputFileName, m_options.data(), runImmediately, false, counter++, filePathIn.count(), &applyToAll))
{
- if(appendJob(sourceFileName, outputFileName, m_options, runImmediately))
+ if(appendJob(sourceFileName, outputFileName, m_options.data(), runImmediately))
{
continue;
}
//Add remaining files
while(applyToAll && (iter != filePathIn.constEnd()))
{
- const bool runImmediatelyTmp = runImmediately && (countRunningJobs() < (m_preferences->autoRunNextJob() ? m_preferences->maxRunningJobCount() : 1));
+ const bool runImmediatelyTmp = runImmediately && (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
const QString sourceFileName = *iter;
- const QString outputFileName = AddJobDialog::generateOutputFileName(sourceFileName, m_recentlyUsed->outputDirectory(), m_recentlyUsed->filterIndex(), m_preferences->saveToSourcePath());
- if(!appendJob(sourceFileName, outputFileName, m_options, runImmediatelyTmp))
+ const QString outputFileName = AddJobDialog::generateOutputFileName(sourceFileName, m_recentlyUsed->outputDirectory(), m_recentlyUsed->filterIndex(), m_preferences->getSaveToSourcePath());
+ if(!appendJob(sourceFileName, outputFileName, m_options.data(), runImmediatelyTmp))
{
return false;
}
return true;
}
-
/*
* Append a new job
*/
bool MainWindow::appendJob(const QString &sourceFileName, const QString &outputFileName, OptionsModel *options, const bool runImmediately)
{
bool okay = false;
-
- EncodeThread *thrd = new EncodeThread
- (
- sourceFileName,
- outputFileName,
- options,
- QString("%1/toolset").arg(m_appDir),
- m_vapoursynthPath,
- m_cpuFeatures->x64,
- m_preferences->use10BitEncoding(),
- m_cpuFeatures->x64 && m_preferences->useAvisyth64Bit(),
- m_skipVersionTest,
- m_preferences->processPriority(),
- m_abortOnTimeout
- );
-
+ EncodeThread *thrd = new EncodeThread(sourceFileName, outputFileName, options, m_sysinfo.data(), m_preferences.data());
QModelIndex newIndex = m_jobList->insertJob(thrd);
if(newIndex.isValid())
{
if(runImmediately)
{
- jobsView->selectRow(newIndex.row());
+ ui->jobsView->selectRow(newIndex.row());
QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
m_jobList->startJob(newIndex);
}
okay = true;
}
- m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
+ m_label[0]->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
return okay;
}
{
qDebug("MainWindow::updateButtons(void)");
- buttonStartJob->setEnabled(status == JobStatus_Enqueued);
- buttonAbortJob->setEnabled(status == JobStatus_Indexing || status == JobStatus_Running || status == JobStatus_Running_Pass1 || status == JobStatus_Running_Pass2 || status == JobStatus_Paused);
- buttonPauseJob->setEnabled(status == JobStatus_Indexing || status == JobStatus_Running || status == JobStatus_Paused || status == JobStatus_Running_Pass1 || status == JobStatus_Running_Pass2);
- buttonPauseJob->setChecked(status == JobStatus_Paused || status == JobStatus_Pausing);
+ ui->buttonStartJob->setEnabled(status == JobStatus_Enqueued);
+ ui->buttonAbortJob->setEnabled(status == JobStatus_Indexing || status == JobStatus_Running || status == JobStatus_Running_Pass1 || status == JobStatus_Running_Pass2 || status == JobStatus_Paused);
+ ui->buttonPauseJob->setEnabled(status == JobStatus_Indexing || status == JobStatus_Running || status == JobStatus_Paused || status == JobStatus_Running_Pass1 || status == JobStatus_Running_Pass2);
+ ui->buttonPauseJob->setChecked(status == JobStatus_Paused || status == JobStatus_Pausing);
- actionJob_Delete->setEnabled(status == JobStatus_Completed || status == JobStatus_Aborted || status == JobStatus_Failed || status == JobStatus_Enqueued);
- actionJob_Restart->setEnabled(status == JobStatus_Completed || status == JobStatus_Aborted || status == JobStatus_Failed || status == JobStatus_Enqueued);
- actionJob_Browse->setEnabled(status == JobStatus_Completed);
+ ui->actionJob_Delete->setEnabled(status == JobStatus_Completed || status == JobStatus_Aborted || status == JobStatus_Failed || status == JobStatus_Enqueued);
+ ui->actionJob_Restart->setEnabled(status == JobStatus_Completed || status == JobStatus_Aborted || status == JobStatus_Failed || status == JobStatus_Enqueued);
+ ui->actionJob_Browse->setEnabled(status == JobStatus_Completed);
+ ui->actionJob_MoveUp->setEnabled(status != JobStatus_Undefined);
+ ui->actionJob_MoveDown->setEnabled(status != JobStatus_Undefined);
- actionJob_Start->setEnabled(buttonStartJob->isEnabled());
- actionJob_Abort->setEnabled(buttonAbortJob->isEnabled());
- actionJob_Pause->setEnabled(buttonPauseJob->isEnabled());
- actionJob_Pause->setChecked(buttonPauseJob->isChecked());
+ ui->actionJob_Start->setEnabled(ui->buttonStartJob->isEnabled());
+ ui->actionJob_Abort->setEnabled(ui->buttonAbortJob->isEnabled());
+ ui->actionJob_Pause->setEnabled(ui->buttonPauseJob->isEnabled());
+ ui->actionJob_Pause->setChecked(ui->buttonPauseJob->isChecked());
- editDetails->setEnabled(status != JobStatus_Paused);
+ ui->editDetails->setEnabled(status != JobStatus_Paused);
}
/*
{
qDebug("MainWindow::updateTaskbar(void)");
+ if(m_taskbar.isNull())
+ {
+ return; /*taskbar object not created yet*/
+ }
+
switch(status)
{
case JobStatus_Undefined:
- WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNoState);
+ m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_NONE);
break;
case JobStatus_Aborting:
case JobStatus_Starting:
case JobStatus_Pausing:
case JobStatus_Resuming:
- WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarIndeterminateState);
+ m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_INTERMEDIATE);
break;
case JobStatus_Aborted:
case JobStatus_Failed:
- WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
+ m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_ERROR);
break;
case JobStatus_Paused:
- WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarPausedState);
+ m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_PAUSED);
break;
default:
- WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
+ m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_NORMAL);
break;
}
case JobStatus_Resuming:
break;
default:
- WinSevenTaskbar::setTaskbarProgress(this, progressBar->value(), progressBar->maximum());
+ m_taskbar->setTaskbarProgress(ui->progressBar->value(), ui->progressBar->maximum());
break;
}
- WinSevenTaskbar::setOverlayIcon(this, icon.isNull() ? NULL : &icon);
+ m_taskbar->setOverlayIcon(icon.isNull() ? NULL : &icon);
}
/*
- * Read Vapursynth location from registry
+ * Parse command-line arguments
*/
-QString MainWindow::getVapoursynthLocation(void)
+bool MainWindow::parseCommandLineArgs(void)
{
- QString vapoursynthPath;
- static const wchar_t *VPS_REG_KEY = L"SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\VapourSynth_is1";
- HKEY hKey = NULL;
+ const MUtils::OS::ArgumentMap &args = MUtils::OS::arguments();
- if(RegOpenKey(HKEY_LOCAL_MACHINE, VPS_REG_KEY, &hKey) == ERROR_SUCCESS)
+ quint32 flags = 0;
+ bool commandSent = false;
+
+ //Handle flags
+ if(args.contains(CLI_PARAM_FORCE_START))
{
- const size_t DATA_LEN = 2048;
- wchar_t data[DATA_LEN];
- DWORD type = REG_NONE, size = sizeof(wchar_t) * DATA_LEN;
- if(RegQueryValueEx(hKey, L"InstallLocation", NULL, &type, ((BYTE*)&data[0]), &size) == ERROR_SUCCESS)
- {
- if((type == REG_SZ) || (type == REG_EXPAND_SZ))
- {
- vapoursynthPath = QDir::fromNativeSeparators(QString::fromUtf16((const ushort*)&data[0]));
- while(vapoursynthPath.endsWith("/")) { vapoursynthPath.chop(1); }
- qDebug("Vapoursynth location: %s", vapoursynthPath.toUtf8().constData());
- }
- }
- RegCloseKey(hKey);
+ flags = ((flags | IPC_FLAG_FORCE_START) & (~IPC_FLAG_FORCE_ENQUEUE));
}
- else
+ if(args.contains(CLI_PARAM_FORCE_ENQUEUE))
{
- qWarning("Vapoursynth registry key not found -> not installed!");
+ flags = ((flags | IPC_FLAG_FORCE_ENQUEUE) & (~IPC_FLAG_FORCE_START));
}
- return vapoursynthPath;
-}
-
-bool MainWindow::checkVapourSynth(QFile *vpsExePath, QFile *vpsDllPath)
-{
- bool okay = false;
- static const char *VSSCRIPT_ENTRY = "_vsscript_init@0";
-
- if(vpsExePath->open(QIODevice::ReadOnly) && vpsDllPath->open(QIODevice::ReadOnly))
+ //Process all command-line arguments
+ if(args.contains(CLI_PARAM_ADD_FILE))
{
- DWORD binaryType;
- if(GetBinaryType(QWCHAR(QDir::toNativeSeparators(vpsExePath->fileName())), &binaryType))
+ foreach(const QString &fileName, args.values(CLI_PARAM_ADD_FILE))
{
- okay = (binaryType == SCS_32BIT_BINARY || binaryType == SCS_64BIT_BINARY);
+ handleCommand(IPC_OPCODE_ADD_FILE, QStringList() << fileName, flags);
}
+ commandSent = true;
}
-
- if(okay)
+ if(args.contains(CLI_PARAM_ADD_JOB))
{
- qDebug("VapourSynth binaries found -> load VSSCRIPT.DLL");
- QLibrary vspLibrary("vsscript.dll");
- if(okay = vspLibrary.load())
+ foreach(const QString &options, args.values(CLI_PARAM_ADD_JOB))
{
- if(!(okay = (vspLibrary.resolve(VSSCRIPT_ENTRY) != NULL)))
+ const QStringList optionValues = options.split('|', QString::SkipEmptyParts);
+ if(optionValues.count() == 3)
{
- qWarning("Entrypoint '%s' not found in VSSCRIPT.DLL !!!", VSSCRIPT_ENTRY);
+ handleCommand(IPC_OPCODE_ADD_JOB, optionValues, flags);
+ }
+ else
+ {
+ qWarning("Invalid number of arguments for parameter \"--%s\" detected!", CLI_PARAM_ADD_JOB);
}
}
- else
- {
- qWarning("Failed to load VSSCRIPT.DLL !!!");
- }
- }
- else
- {
- qWarning("VapourSynth binaries could not be found !!!");
+ commandSent = true;
}
- return okay;
+ return commandSent;
}