PageRenderTime 61ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/src/win_main.cpp

https://bitbucket.org/lord_mulder/simple-x264-launcher
C++ | 1240 lines | 933 code | 139 blank | 168 comment | 216 complexity | eab823b77390c754dcedd568e355a170 MD5 | raw file
Possible License(s): LGPL-2.0, LGPL-2.1, GPL-2.0
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // Simple x264 Launcher
  3. // Copyright (C) 2004-2013 LoRd_MuldeR <MuldeR2@GMX.de>
  4. //
  5. // This program is free software; you can redistribute it and/or modify
  6. // it under the terms of the GNU General Public License as published by
  7. // the Free Software Foundation; either version 2 of the License, or
  8. // (at your option) any later version.
  9. //
  10. // This program is distributed in the hope that it will be useful,
  11. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. // GNU General Public License for more details.
  14. //
  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.
  18. //
  19. // http://www.gnu.org/licenses/gpl-2.0.txt
  20. ///////////////////////////////////////////////////////////////////////////////
  21. #include "win_main.h"
  22. #include "model_jobList.h"
  23. #include "model_options.h"
  24. #include "thread_avisynth.h"
  25. #include "taskbar7.h"
  26. #include "resource.h"
  27. #include <QDate>
  28. #include <QTimer>
  29. #include <QCloseEvent>
  30. #include <QMessageBox>
  31. #include <QDesktopServices>
  32. #include <QUrl>
  33. #include <QDir>
  34. #include <QLibrary>
  35. #include <QProcess>
  36. #include <QProgressDialog>
  37. #include <QScrollBar>
  38. #include <QTextStream>
  39. #include <QSettings>
  40. #include <QFileDialog>
  41. #include <Mmsystem.h>
  42. const char *home_url = "http://muldersoft.com/";
  43. const char *update_url = "http://code.google.com/p/mulder/downloads/list";
  44. const char *tpl_last = "<LAST_USED>";
  45. #define SET_FONT_BOLD(WIDGET,BOLD) { QFont _font = WIDGET->font(); _font.setBold(BOLD); WIDGET->setFont(_font); }
  46. #define SET_TEXT_COLOR(WIDGET,COLOR) { QPalette _palette = WIDGET->palette(); _palette.setColor(QPalette::WindowText, (COLOR)); _palette.setColor(QPalette::Text, (COLOR)); WIDGET->setPalette(_palette); }
  47. static int exceptionFilter(_EXCEPTION_RECORD *dst, _EXCEPTION_POINTERS *src) { memcpy(dst, src->ExceptionRecord, sizeof(_EXCEPTION_RECORD)); return EXCEPTION_EXECUTE_HANDLER; }
  48. ///////////////////////////////////////////////////////////////////////////////
  49. // Constructor & Destructor
  50. ///////////////////////////////////////////////////////////////////////////////
  51. /*
  52. * Constructor
  53. */
  54. MainWindow::MainWindow(const x264_cpu_t *const cpuFeatures)
  55. :
  56. m_cpuFeatures(cpuFeatures),
  57. m_appDir(QApplication::applicationDirPath()),
  58. m_options(NULL),
  59. m_jobList(NULL),
  60. m_droppedFiles(NULL),
  61. m_firstShow(true)
  62. {
  63. //Init the dialog, from the .ui file
  64. setupUi(this);
  65. setWindowFlags(windowFlags() & (~Qt::WindowMaximizeButtonHint));
  66. //Register meta types
  67. qRegisterMetaType<QUuid>("QUuid");
  68. qRegisterMetaType<QUuid>("DWORD");
  69. qRegisterMetaType<EncodeThread::JobStatus>("EncodeThread::JobStatus");
  70. //Load preferences
  71. PreferencesDialog::initPreferences(&m_preferences);
  72. PreferencesDialog::loadPreferences(&m_preferences);
  73. //Load recently used
  74. AddJobDialog::initRecentlyUsed(&m_recentlyUsed);
  75. AddJobDialog::loadRecentlyUsed(&m_recentlyUsed);
  76. //Create options object
  77. m_options = new OptionsModel();
  78. OptionsModel::loadTemplate(m_options, QString::fromLatin1(tpl_last));
  79. //Create IPC thread object
  80. m_ipcThread = new IPCThread();
  81. connect(m_ipcThread, SIGNAL(instanceCreated(DWORD)), this, SLOT(instanceCreated(DWORD)), Qt::QueuedConnection);
  82. //Freeze minimum size
  83. setMinimumSize(size());
  84. splitter->setSizes(QList<int>() << 16 << 196);
  85. //Update title
  86. labelBuildDate->setText(tr("Built on %1 at %2").arg(x264_version_date().toString(Qt::ISODate), QString::fromLatin1(x264_version_time())));
  87. labelBuildDate->installEventFilter(this);
  88. setWindowTitle(QString("%1 (%2 Mode)").arg(windowTitle(), m_cpuFeatures->x64 ? "64-Bit" : "32-Bit"));
  89. if(X264_DEBUG)
  90. {
  91. setWindowTitle(QString("%1 | !!! DEBUG VERSION !!!").arg(windowTitle()));
  92. setStyleSheet("QMenuBar, QMainWindow { background-color: yellow }");
  93. }
  94. else if(x264_is_prerelease())
  95. {
  96. setWindowTitle(QString("%1 | PRE-RELEASE VERSION").arg(windowTitle()));
  97. }
  98. //Create model
  99. m_jobList = new JobListModel();
  100. connect(m_jobList, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(jobChangedData(QModelIndex, QModelIndex)));
  101. jobsView->setModel(m_jobList);
  102. //Setup view
  103. jobsView->horizontalHeader()->setSectionHidden(3, true);
  104. jobsView->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
  105. jobsView->horizontalHeader()->setResizeMode(1, QHeaderView::Fixed);
  106. jobsView->horizontalHeader()->setResizeMode(2, QHeaderView::Fixed);
  107. jobsView->horizontalHeader()->resizeSection(1, 150);
  108. jobsView->horizontalHeader()->resizeSection(2, 90);
  109. jobsView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
  110. connect(jobsView->selectionModel(), SIGNAL(currentChanged(QModelIndex, QModelIndex)), this, SLOT(jobSelected(QModelIndex, QModelIndex)));
  111. //Create context menu
  112. QAction *actionClipboard = new QAction(QIcon(":/buttons/page_paste.png"), tr("Copy to Clipboard"), logView);
  113. actionClipboard->setEnabled(false);
  114. logView->addAction(actionClipboard);
  115. connect(actionClipboard, SIGNAL(triggered(bool)), this, SLOT(copyLogToClipboard(bool)));
  116. jobsView->addActions(menuJob->actions());
  117. //Enable buttons
  118. connect(buttonAddJob, SIGNAL(clicked()), this, SLOT(addButtonPressed()));
  119. connect(buttonStartJob, SIGNAL(clicked()), this, SLOT(startButtonPressed()));
  120. connect(buttonAbortJob, SIGNAL(clicked()), this, SLOT(abortButtonPressed()));
  121. connect(buttonPauseJob, SIGNAL(toggled(bool)), this, SLOT(pauseButtonPressed(bool)));
  122. connect(actionJob_Delete, SIGNAL(triggered()), this, SLOT(deleteButtonPressed()));
  123. connect(actionJob_Restart, SIGNAL(triggered()), this, SLOT(restartButtonPressed()));
  124. connect(actionJob_Browse, SIGNAL(triggered()), this, SLOT(browseButtonPressed()));
  125. //Enable menu
  126. connect(actionOpen, SIGNAL(triggered()), this, SLOT(openActionTriggered()));
  127. connect(actionAbout, SIGNAL(triggered()), this, SLOT(showAbout()));
  128. connect(actionWebMulder, SIGNAL(triggered()), this, SLOT(showWebLink()));
  129. connect(actionWebX264, SIGNAL(triggered()), this, SLOT(showWebLink()));
  130. connect(actionWebKomisar, SIGNAL(triggered()), this, SLOT(showWebLink()));
  131. connect(actionWebJarod, SIGNAL(triggered()), this, SLOT(showWebLink()));
  132. connect(actionWebJEEB, SIGNAL(triggered()), this, SLOT(showWebLink()));
  133. connect(actionWebAvisynth32, SIGNAL(triggered()), this, SLOT(showWebLink()));
  134. connect(actionWebAvisynth64, SIGNAL(triggered()), this, SLOT(showWebLink()));
  135. connect(actionWebWiki, SIGNAL(triggered()), this, SLOT(showWebLink()));
  136. connect(actionWebBluRay, SIGNAL(triggered()), this, SLOT(showWebLink()));
  137. connect(actionWebAvsWiki, SIGNAL(triggered()), this, SLOT(showWebLink()));
  138. connect(actionWebSecret, SIGNAL(triggered()), this, SLOT(showWebLink()));
  139. connect(actionWebSupport, SIGNAL(triggered()), this, SLOT(showWebLink()));
  140. connect(actionPreferences, SIGNAL(triggered()), this, SLOT(showPreferences()));
  141. //Create floating label
  142. m_label = new QLabel(jobsView->viewport());
  143. m_label->setText(tr("No job created yet. Please click the 'Add New Job' button!"));
  144. m_label->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
  145. SET_TEXT_COLOR(m_label, Qt::darkGray);
  146. SET_FONT_BOLD(m_label, true);
  147. m_label->setVisible(true);
  148. m_label->setContextMenuPolicy(Qt::ActionsContextMenu);
  149. m_label->addActions(jobsView->actions());
  150. connect(splitter, SIGNAL(splitterMoved(int, int)), this, SLOT(updateLabelPos()));
  151. updateLabelPos();
  152. }
  153. /*
  154. * Destructor
  155. */
  156. MainWindow::~MainWindow(void)
  157. {
  158. OptionsModel::saveTemplate(m_options, QString::fromLatin1(tpl_last));
  159. X264_DELETE(m_jobList);
  160. X264_DELETE(m_options);
  161. X264_DELETE(m_droppedFiles);
  162. X264_DELETE(m_label);
  163. while(!m_toolsList.isEmpty())
  164. {
  165. QFile *temp = m_toolsList.takeFirst();
  166. X264_DELETE(temp);
  167. }
  168. if(m_ipcThread->isRunning())
  169. {
  170. m_ipcThread->setAbort();
  171. if(!m_ipcThread->wait(5000))
  172. {
  173. m_ipcThread->terminate();
  174. m_ipcThread->wait();
  175. }
  176. }
  177. X264_DELETE(m_ipcThread);
  178. AvisynthCheckThread::unload();
  179. }
  180. ///////////////////////////////////////////////////////////////////////////////
  181. // Slots
  182. ///////////////////////////////////////////////////////////////////////////////
  183. /*
  184. * The "add" button was clicked
  185. */
  186. void MainWindow::addButtonPressed()
  187. {
  188. qDebug("MainWindow::addButtonPressed");
  189. bool runImmediately = (countRunningJobs() < (m_preferences.autoRunNextJob ? m_preferences.maxRunningJobCount : 1));
  190. QString sourceFileName, outputFileName;
  191. if(createJob(sourceFileName, outputFileName, m_options, runImmediately))
  192. {
  193. appendJob(sourceFileName, outputFileName, m_options, runImmediately);
  194. }
  195. }
  196. /*
  197. * The "open" action was triggered
  198. */
  199. void MainWindow::openActionTriggered()
  200. {
  201. QStringList fileList = QFileDialog::getOpenFileNames(this, tr("Open Source File(s)"), m_recentlyUsed.sourceDirectory, AddJobDialog::getInputFilterLst(), NULL, QFileDialog::DontUseNativeDialog);
  202. if(!fileList.empty())
  203. {
  204. m_recentlyUsed.sourceDirectory = QFileInfo(fileList.last()).absolutePath();
  205. if(fileList.count() > 1)
  206. {
  207. createJobMultiple(fileList);
  208. }
  209. else
  210. {
  211. bool runImmediately = (countRunningJobs() < (m_preferences.autoRunNextJob ? m_preferences.maxRunningJobCount : 1));
  212. QString sourceFileName(fileList.first()), outputFileName;
  213. if(createJob(sourceFileName, outputFileName, m_options, runImmediately))
  214. {
  215. appendJob(sourceFileName, outputFileName, m_options, runImmediately);
  216. }
  217. }
  218. }
  219. }
  220. /*
  221. * The "start" button was clicked
  222. */
  223. void MainWindow::startButtonPressed(void)
  224. {
  225. m_jobList->startJob(jobsView->currentIndex());
  226. }
  227. /*
  228. * The "abort" button was clicked
  229. */
  230. void MainWindow::abortButtonPressed(void)
  231. {
  232. m_jobList->abortJob(jobsView->currentIndex());
  233. }
  234. /*
  235. * The "delete" button was clicked
  236. */
  237. void MainWindow::deleteButtonPressed(void)
  238. {
  239. m_jobList->deleteJob(jobsView->currentIndex());
  240. m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
  241. }
  242. /*
  243. * The "browse" button was clicked
  244. */
  245. void MainWindow::browseButtonPressed(void)
  246. {
  247. QString outputFile = m_jobList->getJobOutputFile(jobsView->currentIndex());
  248. if((!outputFile.isEmpty()) && QFileInfo(outputFile).exists() && QFileInfo(outputFile).isFile())
  249. {
  250. QProcess::startDetached(QString::fromLatin1("explorer.exe"), QStringList() << QString::fromLatin1("/select,") << QDir::toNativeSeparators(outputFile), QFileInfo(outputFile).path());
  251. }
  252. else
  253. {
  254. QMessageBox::warning(this, tr("Not Found"), tr("Sorry, the output file could not be found!"));
  255. }
  256. }
  257. /*
  258. * The "pause" button was clicked
  259. */
  260. void MainWindow::pauseButtonPressed(bool checked)
  261. {
  262. if(checked)
  263. {
  264. m_jobList->pauseJob(jobsView->currentIndex());
  265. }
  266. else
  267. {
  268. m_jobList->resumeJob(jobsView->currentIndex());
  269. }
  270. }
  271. /*
  272. * The "restart" button was clicked
  273. */
  274. void MainWindow::restartButtonPressed(void)
  275. {
  276. const QModelIndex index = jobsView->currentIndex();
  277. const OptionsModel *options = m_jobList->getJobOptions(index);
  278. QString sourceFileName = m_jobList->getJobSourceFile(index);
  279. QString outputFileName = m_jobList->getJobOutputFile(index);
  280. if((options) && (!sourceFileName.isEmpty()) && (!outputFileName.isEmpty()))
  281. {
  282. bool runImmediately = true;
  283. OptionsModel *tempOptions = new OptionsModel(*options);
  284. if(createJob(sourceFileName, outputFileName, tempOptions, runImmediately, true))
  285. {
  286. appendJob(sourceFileName, outputFileName, tempOptions, runImmediately);
  287. }
  288. X264_DELETE(tempOptions);
  289. }
  290. }
  291. /*
  292. * Job item selected by user
  293. */
  294. void MainWindow::jobSelected(const QModelIndex & current, const QModelIndex & previous)
  295. {
  296. qDebug("Job selected: %d", current.row());
  297. if(logView->model())
  298. {
  299. disconnect(logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
  300. }
  301. if(current.isValid())
  302. {
  303. logView->setModel(m_jobList->getLogFile(current));
  304. connect(logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
  305. logView->actions().first()->setEnabled(true);
  306. QTimer::singleShot(0, logView, SLOT(scrollToBottom()));
  307. progressBar->setValue(m_jobList->getJobProgress(current));
  308. editDetails->setText(m_jobList->data(m_jobList->index(current.row(), 3, QModelIndex()), Qt::DisplayRole).toString());
  309. updateButtons(m_jobList->getJobStatus(current));
  310. updateTaskbar(m_jobList->getJobStatus(current), m_jobList->data(m_jobList->index(current.row(), 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
  311. }
  312. else
  313. {
  314. logView->setModel(NULL);
  315. logView->actions().first()->setEnabled(false);
  316. progressBar->setValue(0);
  317. editDetails->clear();
  318. updateButtons(EncodeThread::JobStatus_Undefined);
  319. updateTaskbar(EncodeThread::JobStatus_Undefined, QIcon());
  320. }
  321. progressBar->repaint();
  322. }
  323. /*
  324. * Handle update of job info (status, progress, details, etc)
  325. */
  326. void MainWindow::jobChangedData(const QModelIndex &topLeft, const QModelIndex &bottomRight)
  327. {
  328. int selected = jobsView->currentIndex().row();
  329. if(topLeft.column() <= 1 && bottomRight.column() >= 1) /*STATUS*/
  330. {
  331. for(int i = topLeft.row(); i <= bottomRight.row(); i++)
  332. {
  333. EncodeThread::JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
  334. if(i == selected)
  335. {
  336. qDebug("Current job changed status!");
  337. updateButtons(status);
  338. updateTaskbar(status, m_jobList->data(m_jobList->index(i, 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
  339. }
  340. if((status == EncodeThread::JobStatus_Completed) || (status == EncodeThread::JobStatus_Failed))
  341. {
  342. if(m_preferences.autoRunNextJob) QTimer::singleShot(0, this, SLOT(launchNextJob()));
  343. if(m_preferences.shutdownComputer) QTimer::singleShot(0, this, SLOT(shutdownComputer()));
  344. if(m_preferences.saveLogFiles) saveLogFile(m_jobList->index(i, 1, QModelIndex()));
  345. }
  346. }
  347. }
  348. if(topLeft.column() <= 2 && bottomRight.column() >= 2) /*PROGRESS*/
  349. {
  350. for(int i = topLeft.row(); i <= bottomRight.row(); i++)
  351. {
  352. if(i == selected)
  353. {
  354. progressBar->setValue(m_jobList->getJobProgress(m_jobList->index(i, 0, QModelIndex())));
  355. WinSevenTaskbar::setTaskbarProgress(this, progressBar->value(), progressBar->maximum());
  356. break;
  357. }
  358. }
  359. }
  360. if(topLeft.column() <= 3 && bottomRight.column() >= 3) /*DETAILS*/
  361. {
  362. for(int i = topLeft.row(); i <= bottomRight.row(); i++)
  363. {
  364. if(i == selected)
  365. {
  366. editDetails->setText(m_jobList->data(m_jobList->index(i, 3, QModelIndex()), Qt::DisplayRole).toString());
  367. break;
  368. }
  369. }
  370. }
  371. }
  372. /*
  373. * Handle new log file content
  374. */
  375. void MainWindow::jobLogExtended(const QModelIndex & parent, int start, int end)
  376. {
  377. QTimer::singleShot(0, logView, SLOT(scrollToBottom()));
  378. }
  379. /*
  380. * About screen
  381. */
  382. void MainWindow::showAbout(void)
  383. {
  384. QString text;
  385. 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());
  386. text += QString().sprintf("Copyright (c) 2004-%04d LoRd_MuldeR &lt;mulder2@gmx.de&gt;. Some rights reserved.<br>", qMax(x264_version_date().year(),QDate::currentDate().year()));
  387. 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());
  388. text += QString().sprintf("This program is free software: you can redistribute it and/or modify<br>");
  389. text += QString().sprintf("it under the terms of the GNU General Public License &lt;http://www.gnu.org/&gt;.<br>");
  390. text += QString().sprintf("Note that this program is distributed with ABSOLUTELY NO WARRANTY.<br><br>");
  391. text += QString().sprintf("Please check the web-site at <a href=\"%s\">%s</a> for updates !!!<br></tt></nobr>", home_url, home_url);
  392. QMessageBox aboutBox(this);
  393. aboutBox.setIconPixmap(QIcon(":/images/movie.png").pixmap(64,64));
  394. aboutBox.setWindowTitle(tr("About..."));
  395. aboutBox.setText(text.replace("-", "&minus;"));
  396. aboutBox.addButton(tr("About x264"), QMessageBox::NoRole);
  397. aboutBox.addButton(tr("About AVS"), QMessageBox::NoRole);
  398. aboutBox.addButton(tr("About Qt"), QMessageBox::NoRole);
  399. aboutBox.setEscapeButton(aboutBox.addButton(tr("Close"), QMessageBox::NoRole));
  400. forever
  401. {
  402. MessageBeep(MB_ICONINFORMATION);
  403. switch(aboutBox.exec())
  404. {
  405. case 0:
  406. {
  407. QString text2;
  408. text2 += tr("<nobr><tt>x264 - the best H.264/AVC encoder. Copyright (c) 2003-2013 x264 project.<br>");
  409. text2 += tr("Free software library for encoding video streams into the H.264/MPEG-4 AVC format.<br>");
  410. text2 += tr("Released under the terms of the GNU General Public License.<br><br>");
  411. text2 += tr("Please visit <a href=\"%1\">%1</a> for obtaining a commercial x264 license.<br>").arg("http://x264licensing.com/");
  412. 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");
  413. QMessageBox x264Box(this);
  414. x264Box.setIconPixmap(QIcon(":/images/x264.png").pixmap(48,48));
  415. x264Box.setWindowTitle(tr("About x264"));
  416. x264Box.setText(text2.replace("-", "&minus;"));
  417. x264Box.setEscapeButton(x264Box.addButton(tr("Close"), QMessageBox::NoRole));
  418. MessageBeep(MB_ICONINFORMATION);
  419. x264Box.exec();
  420. }
  421. break;
  422. case 1:
  423. {
  424. QString text2;
  425. text2 += tr("<nobr><tt>Avisynth - powerful video processing scripting language.<br>");
  426. text2 += tr("Copyright (c) 2000 Ben Rudiak-Gould and all subsequent developers.<br>");
  427. text2 += tr("Released under the terms of the GNU General Public License.<br><br>");
  428. text2 += tr("Please visit the web-site <a href=\"%1\">%1</a> for more information.<br>").arg("http://avisynth.org/");
  429. 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");
  430. QMessageBox x264Box(this);
  431. x264Box.setIconPixmap(QIcon(":/images/avisynth.png").pixmap(48,67));
  432. x264Box.setWindowTitle(tr("About Avisynth"));
  433. x264Box.setText(text2.replace("-", "&minus;"));
  434. x264Box.setEscapeButton(x264Box.addButton(tr("Close"), QMessageBox::NoRole));
  435. MessageBeep(MB_ICONINFORMATION);
  436. x264Box.exec();
  437. }
  438. break;
  439. case 2:
  440. QMessageBox::aboutQt(this);
  441. break;
  442. default:
  443. return;
  444. }
  445. }
  446. }
  447. /*
  448. * Open web-link
  449. */
  450. void MainWindow::showWebLink(void)
  451. {
  452. if(QObject::sender() == actionWebMulder) QDesktopServices::openUrl(QUrl(home_url));
  453. if(QObject::sender() == actionWebX264) QDesktopServices::openUrl(QUrl("http://www.x264.com/"));
  454. if(QObject::sender() == actionWebKomisar) QDesktopServices::openUrl(QUrl("http://komisar.gin.by/"));
  455. if(QObject::sender() == actionWebJarod) QDesktopServices::openUrl(QUrl("http://www.x264.nl/"));
  456. if(QObject::sender() == actionWebJEEB) QDesktopServices::openUrl(QUrl("http://x264.fushizen.eu/"));
  457. if(QObject::sender() == actionWebAvisynth32) QDesktopServices::openUrl(QUrl("http://sourceforge.net/projects/avisynth2/files/AviSynth%202.5/"));
  458. if(QObject::sender() == actionWebAvisynth64) QDesktopServices::openUrl(QUrl("http://code.google.com/p/avisynth64/downloads/list"));
  459. if(QObject::sender() == actionWebWiki) QDesktopServices::openUrl(QUrl("http://mewiki.project357.com/wiki/X264_Settings"));
  460. if(QObject::sender() == actionWebBluRay) QDesktopServices::openUrl(QUrl("http://www.x264bluray.com/"));
  461. if(QObject::sender() == actionWebAvsWiki) QDesktopServices::openUrl(QUrl("http://avisynth.org/mediawiki/Main_Page#Usage"));
  462. if(QObject::sender() == actionWebSupport) QDesktopServices::openUrl(QUrl("http://forum.doom9.org/showthread.php?t=144140"));
  463. if(QObject::sender() == actionWebSecret) QDesktopServices::openUrl(QUrl("http://www.youtube.com/watch_popup?v=AXIeHY-OYNI"));
  464. }
  465. /*
  466. * Pereferences dialog
  467. */
  468. void MainWindow::showPreferences(void)
  469. {
  470. PreferencesDialog *preferences = new PreferencesDialog(this, &m_preferences, m_cpuFeatures->x64);
  471. preferences->exec();
  472. X264_DELETE(preferences);
  473. }
  474. /*
  475. * Launch next job, after running job has finished
  476. */
  477. void MainWindow::launchNextJob(void)
  478. {
  479. qDebug("launchNextJob(void)");
  480. const int rows = m_jobList->rowCount(QModelIndex());
  481. if(countRunningJobs() >= m_preferences.maxRunningJobCount)
  482. {
  483. qDebug("Still have too many jobs running, won't launch next one yet!");
  484. return;
  485. }
  486. int startIdx= jobsView->currentIndex().isValid() ? qBound(0, jobsView->currentIndex().row(), rows-1) : 0;
  487. for(int i = 0; i < rows; i++)
  488. {
  489. int currentIdx = (i + startIdx) % rows;
  490. EncodeThread::JobStatus status = m_jobList->getJobStatus(m_jobList->index(currentIdx, 0, QModelIndex()));
  491. if(status == EncodeThread::JobStatus_Enqueued)
  492. {
  493. if(m_jobList->startJob(m_jobList->index(currentIdx, 0, QModelIndex())))
  494. {
  495. jobsView->selectRow(currentIdx);
  496. return;
  497. }
  498. }
  499. }
  500. qWarning("No enqueued jobs left!");
  501. }
  502. /*
  503. * Save log to text file
  504. */
  505. void MainWindow::saveLogFile(const QModelIndex &index)
  506. {
  507. if(index.isValid())
  508. {
  509. if(LogFileModel *log = m_jobList->getLogFile(index))
  510. {
  511. QDir(QString("%1/logs").arg(x264_data_path())).mkpath(".");
  512. QString logFilePath = QString("%1/logs/LOG.%2.%3.txt").arg(x264_data_path(), QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString(Qt::ISODate).replace(':', "-"));
  513. QFile outFile(logFilePath);
  514. if(outFile.open(QIODevice::WriteOnly))
  515. {
  516. QTextStream outStream(&outFile);
  517. outStream.setCodec("UTF-8");
  518. outStream.setGenerateByteOrderMark(true);
  519. const int rows = log->rowCount(QModelIndex());
  520. for(int i = 0; i < rows; i++)
  521. {
  522. outStream << log->data(log->index(i, 0, QModelIndex()), Qt::DisplayRole).toString() << QLatin1String("\r\n");
  523. }
  524. outFile.close();
  525. }
  526. else
  527. {
  528. qWarning("Failed to open log file for writing:\n%s", logFilePath.toUtf8().constData());
  529. }
  530. }
  531. }
  532. }
  533. /*
  534. * Shut down the computer (with countdown)
  535. */
  536. void MainWindow::shutdownComputer(void)
  537. {
  538. qDebug("shutdownComputer(void)");
  539. if(countPendingJobs() > 0)
  540. {
  541. qDebug("Still have pending jobs, won't shutdown yet!");
  542. return;
  543. }
  544. const int iTimeout = 30;
  545. const Qt::WindowFlags flags = Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowSystemMenuHint;
  546. const QString text = QString("%1%2%1").arg(QString().fill(' ', 18), tr("Warning: Computer will shutdown in %1 seconds..."));
  547. qWarning("Initiating shutdown sequence!");
  548. QProgressDialog progressDialog(text.arg(iTimeout), tr("Cancel Shutdown"), 0, iTimeout + 1, this, flags);
  549. QPushButton *cancelButton = new QPushButton(tr("Cancel Shutdown"), &progressDialog);
  550. cancelButton->setIcon(QIcon(":/buttons/power_on.png"));
  551. progressDialog.setModal(true);
  552. progressDialog.setAutoClose(false);
  553. progressDialog.setAutoReset(false);
  554. progressDialog.setWindowIcon(QIcon(":/buttons/power_off.png"));
  555. progressDialog.setWindowTitle(windowTitle());
  556. progressDialog.setCancelButton(cancelButton);
  557. progressDialog.show();
  558. QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
  559. QApplication::setOverrideCursor(Qt::WaitCursor);
  560. PlaySound(MAKEINTRESOURCE(IDR_WAVE1), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
  561. QApplication::restoreOverrideCursor();
  562. QTimer timer;
  563. timer.setInterval(1000);
  564. timer.start();
  565. QEventLoop eventLoop(this);
  566. connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
  567. connect(&progressDialog, SIGNAL(canceled()), &eventLoop, SLOT(quit()));
  568. for(int i = 1; i <= iTimeout; i++)
  569. {
  570. eventLoop.exec();
  571. if(progressDialog.wasCanceled())
  572. {
  573. progressDialog.close();
  574. return;
  575. }
  576. progressDialog.setValue(i+1);
  577. progressDialog.setLabelText(text.arg(iTimeout-i));
  578. if(iTimeout-i == 3) progressDialog.setCancelButton(NULL);
  579. QApplication::processEvents();
  580. PlaySound(MAKEINTRESOURCE((i < iTimeout) ? IDR_WAVE2 : IDR_WAVE3), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
  581. }
  582. qWarning("Shutting down !!!");
  583. if(x264_shutdown_computer("Simple x264 Launcher: All jobs completed, shutting down!", 10, true))
  584. {
  585. qApp->closeAllWindows();
  586. }
  587. }
  588. /*
  589. * Main initialization function (called only once!)
  590. */
  591. void MainWindow::init(void)
  592. {
  593. 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";
  594. QStringList binaries = QString::fromLatin1(binFiles).split(":", QString::SkipEmptyParts);
  595. updateLabelPos();
  596. //Check for a running instance
  597. bool firstInstance = false;
  598. if(m_ipcThread->initialize(&firstInstance))
  599. {
  600. m_ipcThread->start();
  601. if(!firstInstance)
  602. {
  603. if(!m_ipcThread->wait(5000))
  604. {
  605. 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"));
  606. m_ipcThread->terminate();
  607. m_ipcThread->wait();
  608. }
  609. close(); qApp->exit(-1); return;
  610. }
  611. }
  612. //Check all binaries
  613. while(!binaries.isEmpty())
  614. {
  615. qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
  616. QString current = binaries.takeFirst();
  617. QFile *file = new QFile(QString("%1/toolset/%2").arg(m_appDir, current));
  618. if(file->open(QIODevice::ReadOnly))
  619. {
  620. bool binaryTypeOkay = false;
  621. DWORD binaryType;
  622. if(GetBinaryType(QWCHAR(QDir::toNativeSeparators(file->fileName())), &binaryType))
  623. {
  624. binaryTypeOkay = (binaryType == SCS_32BIT_BINARY || binaryType == SCS_64BIT_BINARY);
  625. }
  626. if(!binaryTypeOkay)
  627. {
  628. QMessageBox::critical(this, tr("Invalid File!"), tr("<nobr>At least on required tool is not a valid Win32 or Win64 binary:<br>%1<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("-", "&minus;"));
  629. qFatal(QString("Binary is invalid: %1/toolset/%2").arg(m_appDir, current).toLatin1().constData());
  630. close(); qApp->exit(-1); return;
  631. }
  632. m_toolsList << file;
  633. }
  634. else
  635. {
  636. X264_DELETE(file);
  637. QMessageBox::critical(this, tr("File Not Found!"), tr("<nobr>At least on required tool could not be found:<br>%1<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("-", "&minus;"));
  638. qFatal(QString("Binary not found: %1/toolset/%2").arg(m_appDir, current).toLatin1().constData());
  639. close(); qApp->exit(-1); return;
  640. }
  641. }
  642. //Check for portable mode
  643. if(x264_portable())
  644. {
  645. bool ok = false;
  646. static const char *data = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
  647. QFile writeTest(QString("%1/%2").arg(x264_data_path(), QUuid::createUuid().toString()));
  648. if(writeTest.open(QIODevice::WriteOnly))
  649. {
  650. ok = (writeTest.write(data) == strlen(data));
  651. writeTest.remove();
  652. }
  653. if(!ok)
  654. {
  655. 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"));
  656. if(val != 1) { close(); qApp->exit(-1); return; }
  657. }
  658. }
  659. //Pre-release popup
  660. if(x264_is_prerelease())
  661. {
  662. qsrand(time(NULL)); int rnd = qrand() % 3;
  663. 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);
  664. if(rnd != val) { close(); qApp->exit(-1); return; }
  665. }
  666. //Make sure this CPU can run x264 (requires MMX + MMXEXT/iSSE to run x264 with ASM enabled, additionally requires SSE1 for most x264 builds)
  667. if(!(m_cpuFeatures->mmx && m_cpuFeatures->mmx2))
  668. {
  669. 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"));
  670. qFatal("System does not support MMX and MMXEXT, x264 will not work !!!");
  671. close(); qApp->exit(-1); return;
  672. }
  673. else if(!(m_cpuFeatures->mmx && m_cpuFeatures->sse))
  674. {
  675. qWarning("WARNING: System does not support SSE1, most x264 builds will not work !!!\n");
  676. 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"));
  677. if(val != 1) { close(); qApp->exit(-1); return; }
  678. }
  679. //Check for Avisynth support
  680. if(!qApp->arguments().contains("--skip-avisynth-check", Qt::CaseInsensitive))
  681. {
  682. qDebug("[Check for Avisynth support]");
  683. volatile double avisynthVersion = 0.0;
  684. const int result = AvisynthCheckThread::detect(&avisynthVersion);
  685. if(result < 0)
  686. {
  687. QString text = tr("A critical error was encountered while checking your Avisynth version.").append("<br>");
  688. text += tr("This is most likely caused by an erroneous Avisynth Plugin, please try to clean your Plugins folder!").append("<br>");
  689. text += tr("We suggest to move all .dll and .avsi files out of your Avisynth Plugins folder and try again.");
  690. int val = QMessageBox::critical(this, tr("Avisynth Error"), QString("<nobr>%1</nobr>").arg(text).replace("-", "&minus;"), tr("Quit"), tr("Ignore"));
  691. if(val != 1) { close(); qApp->exit(-1); return; }
  692. }
  693. if((!result) || (avisynthVersion < 2.5))
  694. {
  695. 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("-", "&minus;"), tr("Quit"), tr("Ignore"));
  696. if(val != 1) { close(); qApp->exit(-1); return; }
  697. }
  698. qDebug("");
  699. }
  700. //Check for expiration
  701. if(x264_version_date().addMonths(6) < QDate::currentDate())
  702. {
  703. QMessageBox msgBox(this);
  704. msgBox.setIconPixmap(QIcon(":/images/update.png").pixmap(56,56));
  705. msgBox.setWindowTitle(tr("Update Notification"));
  706. msgBox.setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
  707. 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("-", "&minus;").arg(update_url));
  708. QPushButton *btn1 = msgBox.addButton(tr("Discard"), QMessageBox::NoRole);
  709. QPushButton *btn2 = msgBox.addButton(tr("Discard"), QMessageBox::AcceptRole);
  710. btn1->setEnabled(false);
  711. btn2->setVisible(false);
  712. QTimer::singleShot(5000, btn1, SLOT(hide()));
  713. QTimer::singleShot(5000, btn2, SLOT(show()));
  714. msgBox.exec();
  715. }
  716. //Add files from command-line
  717. bool bAddFile = false;
  718. QStringList files, args = qApp->arguments();
  719. while(!args.isEmpty())
  720. {
  721. QString current = args.takeFirst();
  722. if(!bAddFile)
  723. {
  724. bAddFile = (current.compare("--add", Qt::CaseInsensitive) == 0);
  725. continue;
  726. }
  727. if((!current.startsWith("--")) && QFileInfo(current).exists() && QFileInfo(current).isFile())
  728. {
  729. files << QFileInfo(current).canonicalFilePath();
  730. }
  731. }
  732. if(files.count() > 0)
  733. {
  734. createJobMultiple(files);
  735. }
  736. //Enable drag&drop support for this window, required for Qt v4.8.4+
  737. setAcceptDrops(true);
  738. }
  739. /*
  740. * Update the label position
  741. */
  742. void MainWindow::updateLabelPos(void)
  743. {
  744. const QWidget *const viewPort = jobsView->viewport();
  745. m_label->setGeometry(0, 0, viewPort->width(), viewPort->height());
  746. }
  747. /*
  748. * Copy the complete log to the clipboard
  749. */
  750. void MainWindow::copyLogToClipboard(bool checked)
  751. {
  752. qDebug("copyLogToClipboard");
  753. if(LogFileModel *log = dynamic_cast<LogFileModel*>(logView->model()))
  754. {
  755. log->copyToClipboard();
  756. MessageBeep(MB_ICONINFORMATION);
  757. }
  758. }
  759. /*
  760. * Process the dropped files
  761. */
  762. void MainWindow::handleDroppedFiles(void)
  763. {
  764. qDebug("MainWindow::handleDroppedFiles");
  765. if(m_droppedFiles)
  766. {
  767. QStringList droppedFiles(*m_droppedFiles);
  768. m_droppedFiles->clear();
  769. createJobMultiple(droppedFiles);
  770. }
  771. qDebug("Leave from MainWindow::handleDroppedFiles!");
  772. }
  773. void MainWindow::instanceCreated(DWORD pid)
  774. {
  775. qDebug("Notification from other instance (PID=0x%X) received!", pid);
  776. FLASHWINFO flashWinInfo;
  777. memset(&flashWinInfo, 0, sizeof(FLASHWINFO));
  778. flashWinInfo.cbSize = sizeof(FLASHWINFO);
  779. flashWinInfo.hwnd = this->winId();
  780. flashWinInfo.dwFlags = FLASHW_ALL;
  781. flashWinInfo.dwTimeout = 125;
  782. flashWinInfo.uCount = 5;
  783. SwitchToThisWindow(this->winId(), TRUE);
  784. SetForegroundWindow(this->winId());
  785. qApp->processEvents();
  786. FlashWindowEx(&flashWinInfo);
  787. }
  788. ///////////////////////////////////////////////////////////////////////////////
  789. // Event functions
  790. ///////////////////////////////////////////////////////////////////////////////
  791. /*
  792. * Window shown event
  793. */
  794. void MainWindow::showEvent(QShowEvent *e)
  795. {
  796. QMainWindow::showEvent(e);
  797. if(m_firstShow)
  798. {
  799. m_firstShow = false;
  800. QTimer::singleShot(0, this, SLOT(init()));
  801. }
  802. }
  803. /*
  804. * Window close event
  805. */
  806. void MainWindow::closeEvent(QCloseEvent *e)
  807. {
  808. if(countRunningJobs() > 0)
  809. {
  810. e->ignore();
  811. QMessageBox::warning(this, tr("Jobs Are Running"), tr("Sorry, can not exit while there still are running jobs!"));
  812. return;
  813. }
  814. if(countPendingJobs() > 0)
  815. {
  816. 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);
  817. if(ret != QMessageBox::Yes)
  818. {
  819. e->ignore();
  820. return;
  821. }
  822. }
  823. while(m_jobList->rowCount(QModelIndex()) > 0)
  824. {
  825. qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
  826. if(!m_jobList->deleteJob(m_jobList->index(0, 0, QModelIndex())))
  827. {
  828. e->ignore();
  829. QMessageBox::warning(this, tr("Failed To Exit"), tr("Sorry, at least one job could not be deleted!"));
  830. return;
  831. }
  832. }
  833. qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
  834. QMainWindow::closeEvent(e);
  835. }
  836. /*
  837. * Window resize event
  838. */
  839. void MainWindow::resizeEvent(QResizeEvent *e)
  840. {
  841. QMainWindow::resizeEvent(e);
  842. updateLabelPos();
  843. }
  844. /*
  845. * Event filter
  846. */
  847. bool MainWindow::eventFilter(QObject *o, QEvent *e)
  848. {
  849. if((o == labelBuildDate) && (e->type() == QEvent::MouseButtonPress))
  850. {
  851. QTimer::singleShot(0, this, SLOT(showAbout()));
  852. return true;
  853. }
  854. return false;
  855. }
  856. /*
  857. * Win32 message filter
  858. */
  859. bool MainWindow::winEvent(MSG *message, long *result)
  860. {
  861. return WinSevenTaskbar::handleWinEvent(message, result);
  862. }
  863. /*
  864. * File dragged over window
  865. */
  866. void MainWindow::dragEnterEvent(QDragEnterEvent *event)
  867. {
  868. bool accept[2] = {false, false};
  869. foreach(const QString &fmt, event->mimeData()->formats())
  870. {
  871. accept[0] = accept[0] || fmt.contains("text/uri-list", Qt::CaseInsensitive);
  872. accept[1] = accept[1] || fmt.contains("FileNameW", Qt::CaseInsensitive);
  873. }
  874. if(accept[0] && accept[1])
  875. {
  876. event->acceptProposedAction();
  877. }
  878. }
  879. /*
  880. * File dropped onto window
  881. */
  882. void MainWindow::dropEvent(QDropEvent *event)
  883. {
  884. QStringList droppedFiles;
  885. QList<QUrl> urls = event->mimeData()->urls();
  886. while(!urls.isEmpty())
  887. {
  888. QUrl currentUrl = urls.takeFirst();
  889. QFileInfo file(currentUrl.toLocalFile());
  890. if(file.exists() && file.isFile())
  891. {
  892. qDebug("MainWindow::dropEvent: %s", file.canonicalFilePath().toUtf8().constData());
  893. droppedFiles << file.canonicalFilePath();
  894. }
  895. }
  896. if(droppedFiles.count() > 0)
  897. {
  898. if(!m_droppedFiles)
  899. {
  900. m_droppedFiles = new QStringList();
  901. }
  902. m_droppedFiles->append(droppedFiles);
  903. m_droppedFiles->sort();
  904. QTimer::singleShot(0, this, SLOT(handleDroppedFiles()));
  905. }
  906. }
  907. ///////////////////////////////////////////////////////////////////////////////
  908. // Private functions
  909. ///////////////////////////////////////////////////////////////////////////////
  910. /*
  911. * Creates a new job
  912. */
  913. bool MainWindow::createJob(QString &sourceFileName, QString &outputFileName, OptionsModel *options, bool &runImmediately, const bool restart, int fileNo, int fileTotal, bool *applyToAll)
  914. {
  915. bool okay = false;
  916. AddJobDialog *addDialog = new AddJobDialog(this, options, &m_recentlyUsed, m_cpuFeatures->x64, m_preferences.use10BitEncoding, m_preferences.saveToSourcePath);
  917. addDialog->setRunImmediately(runImmediately);
  918. if(!sourceFileName.isEmpty()) addDialog->setSourceFile(sourceFileName);
  919. if(!outputFileName.isEmpty()) addDialog->setOutputFile(outputFileName);
  920. if(restart) addDialog->setWindowTitle(tr("Restart Job"));
  921. const bool multiFile = (fileNo >= 0) && (fileTotal > 1);
  922. if(multiFile)
  923. {
  924. addDialog->setSourceEditable(false);
  925. addDialog->setWindowTitle(addDialog->windowTitle().append(tr(" (File %1 of %2)").arg(QString::number(fileNo+1), QString::number(fileTotal))));
  926. addDialog->setApplyToAllVisible(applyToAll);
  927. }
  928. if(addDialog->exec() == QDialog::Accepted)
  929. {
  930. sourceFileName = addDialog->sourceFile();
  931. outputFileName = addDialog->outputFile();
  932. runImmediately = addDialog->runImmediately();
  933. if(applyToAll)
  934. {
  935. *applyToAll = addDialog->applyToAll();
  936. }
  937. okay = true;
  938. }
  939. X264_DELETE(addDialog);
  940. return okay;
  941. }
  942. /*
  943. * Creates a new job from *multiple* files
  944. */
  945. bool MainWindow::createJobMultiple(const QStringList &filePathIn)
  946. {
  947. QStringList::ConstIterator iter;
  948. bool applyToAll = false, runImmediately = false;
  949. int counter = 0;
  950. //Add files individually
  951. for(iter = filePathIn.constBegin(); (iter != filePathIn.constEnd()) && (!applyToAll); iter++)
  952. {
  953. runImmediately = (countRunningJobs() < (m_preferences.autoRunNextJob ? m_preferences.maxRunningJobCount : 1));
  954. QString sourceFileName(*iter), outputFileName;
  955. if(createJob(sourceFileName, outputFileName, m_options, runImmediately, false, counter++, filePathIn.count(), &applyToAll))
  956. {
  957. if(appendJob(sourceFileName, outputFileName, m_options, runImmediately))
  958. {
  959. continue;
  960. }
  961. }
  962. return false;
  963. }
  964. //Add remaining files
  965. while(applyToAll && (iter != filePathIn.constEnd()))
  966. {
  967. const bool runImmediatelyTmp = runImmediately && (countRunningJobs() < (m_preferences.autoRunNextJob ? m_preferences.maxRunningJobCount : 1));
  968. const QString sourceFileName = *iter;
  969. const QString outputFileName = AddJobDialog::generateOutputFileName(sourceFileName, m_recentlyUsed.outputDirectory, m_recentlyUsed.filterIndex, m_preferences.saveToSourcePath);
  970. if(!appendJob(sourceFileName, outputFileName, m_options, runImmediatelyTmp))
  971. {
  972. return false;
  973. }
  974. iter++;
  975. }
  976. return true;
  977. }
  978. /*
  979. * Append a new job
  980. */
  981. bool MainWindow::appendJob(const QString &sourceFileName, const QString &outputFileName, OptionsModel *options, const bool runImmediately)
  982. {
  983. bool okay = false;
  984. EncodeThread *thrd = new EncodeThread
  985. (
  986. sourceFileName,
  987. outputFileName,
  988. options,
  989. QString("%1/toolset").arg(m_appDir),
  990. m_cpuFeatures->x64,
  991. m_preferences.use10BitEncoding,
  992. m_cpuFeatures->x64 && m_preferences.useAvisyth64Bit
  993. );
  994. QModelIndex newIndex = m_jobList->insertJob(thrd);
  995. if(newIndex.isValid())
  996. {
  997. if(runImmediately)
  998. {
  999. jobsView->selectRow(newIndex.row());
  1000. QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
  1001. m_jobList->startJob(newIndex);
  1002. }
  1003. okay = true;
  1004. }
  1005. m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
  1006. return okay;
  1007. }
  1008. /*
  1009. * Jobs that are not completed (or failed, or aborted) yet
  1010. */
  1011. unsigned int MainWindow::countPendingJobs(void)
  1012. {
  1013. unsigned int count = 0;
  1014. const int rows = m_jobList->rowCount(QModelIndex());
  1015. for(int i = 0; i < rows; i++)
  1016. {
  1017. EncodeThread::JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
  1018. if(status != EncodeThread::JobStatus_Completed && status != EncodeThread::JobStatus_Aborted && status != EncodeThread::JobStatus_Failed)
  1019. {
  1020. count++;
  1021. }
  1022. }
  1023. return count;
  1024. }
  1025. /*
  1026. * Jobs that are still active, i.e. not terminated or enqueued
  1027. */
  1028. unsigned int MainWindow::countRunningJobs(void)
  1029. {
  1030. unsigned int count = 0;
  1031. const int rows = m_jobList->rowCount(QModelIndex());
  1032. for(int i = 0; i < rows; i++)
  1033. {
  1034. EncodeThread::JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
  1035. if(status != EncodeThread::JobStatus_Completed && status != EncodeThread::JobStatus_Aborted && status != EncodeThread::JobStatus_Failed && status != EncodeThread::JobStatus_Enqueued)
  1036. {
  1037. count++;
  1038. }
  1039. }
  1040. return count;
  1041. }
  1042. /*
  1043. * Update all buttons with respect to current job status
  1044. */
  1045. void MainWindow::updateButtons(EncodeThread::JobStatus status)
  1046. {
  1047. qDebug("MainWindow::updateButtons(void)");
  1048. buttonStartJob->setEnabled(status == EncodeThread::JobStatus_Enqueued);
  1049. buttonAbortJob->setEnabled(status == EncodeThread::JobStatus_Indexing || status == EncodeThread::JobStatus_Running || status == EncodeThread::JobStatus_Running_Pass1 || status == EncodeThread::JobStatus_Running_Pass2 || status == EncodeThread::JobStatus_Paused);
  1050. buttonPauseJob->setEnabled(status == EncodeThread::JobStatus_Indexing || status == EncodeThread::JobStatus_Running || status == EncodeThread::JobStatus_Paused || status == EncodeThread::JobStatus_Running_Pass1 || status == EncodeThread::JobStatus_Running_Pass2);
  1051. buttonPauseJob->setChecked(status == EncodeThread::JobStatus_Paused || status == EncodeThread::JobStatus_Pausing);
  1052. actionJob_Delete->setEnabled(status == EncodeThread::JobStatus_Completed || status == EncodeThread::JobStatus_Aborted || status == EncodeThread::JobStatus_Failed || status == EncodeThread::JobStatus_Enqueued);
  1053. actionJob_Restart->setEnabled(status == EncodeThread::JobStatus_Completed || status == EncodeThread::JobStatus_Aborted || status == EncodeThread::JobStatus_Failed || status == EncodeThread::JobStatus_Enqueued);
  1054. actionJob_Browse->setEnabled(status == EncodeThread::JobStatus_Completed);
  1055. actionJob_Start->setEnabled(buttonStartJob->isEnabled());
  1056. actionJob_Abort->setEnabled(buttonAbortJob->isEnabled());
  1057. actionJob_Pause->setEnabled(buttonPauseJob->isEnabled());
  1058. actionJob_Pause->setChecked(buttonPauseJob->isChecked());
  1059. editDetails->setEnabled(status != EncodeThread::JobStatus_Paused);
  1060. }
  1061. /*
  1062. * Update the taskbar with current job status
  1063. */
  1064. void MainWindow::updateTaskbar(EncodeThread::JobStatus status, const QIcon &icon)
  1065. {
  1066. qDebug("MainWindow::updateTaskbar(void)");
  1067. switch(status)
  1068. {
  1069. case EncodeThread::JobStatus_Undefined:
  1070. WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNoState);
  1071. break;
  1072. case EncodeThread::JobStatus_Aborting:
  1073. case EncodeThread::JobStatus_Starting:
  1074. case EncodeThread::JobStatus_Pausing:
  1075. case EncodeThread::JobStatus_Resuming:
  1076. WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarIndeterminateState);
  1077. break;
  1078. case EncodeThread::JobStatus_Aborted:
  1079. case EncodeThread::JobStatus_Failed:
  1080. WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
  1081. break;
  1082. case EncodeThread::JobStatus_Paused:
  1083. WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarPausedState);
  1084. break;
  1085. default:
  1086. WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
  1087. break;
  1088. }
  1089. switch(status)
  1090. {
  1091. case EncodeThread::JobStatus_Aborting:
  1092. case EncodeThread::JobStatus_Starting:
  1093. case EncodeThread::JobStatus_Pausing:
  1094. case EncodeThread::JobStatus_Resuming:
  1095. break;
  1096. default:
  1097. WinSevenTaskbar::setTaskbarProgress(this, progressBar->value(), progressBar->maximum());
  1098. break;
  1099. }
  1100. WinSevenTaskbar::setOverlayIcon(this, icon.isNull() ? NULL : &icon);
  1101. }