PageRenderTime 82ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 0ms

/Utils/x264_x64_v2/src/win_main.cpp

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