1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2010 LoRd_MuldeR <MuldeR2@GMX.de>
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; either version 2 of the License, or
8 // (at your option) any later version.
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License along
16 // with this program; if not, write to the Free Software Foundation, Inc.,
17 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
22 #include "Dialog_Processing.h"
26 #include "Model_FileList.h"
27 #include "Model_Progress.h"
28 #include "Model_Settings.h"
29 #include "Thread_Process.h"
30 #include "Dialog_LogView.h"
31 #include "Encoder_MP3.h"
32 #include "Encoder_Vorbis.h"
33 #include "Encoder_AAC.h"
34 #include "WinSevenTaskbar.h"
36 #include <QApplication>
38 #include <QDesktopWidget>
40 #include <QMessageBox>
42 #include <QCloseEvent>
43 #include <QDesktopServices>
52 #define CHANGE_BACKGROUND_COLOR(WIDGET, COLOR) \
54 QPalette palette = WIDGET->palette(); \
55 palette.setColor(QPalette::Background, COLOR); \
56 WIDGET->setPalette(palette); \
59 ////////////////////////////////////////////////////////////
61 ////////////////////////////////////////////////////////////
63 ProcessingDialog::ProcessingDialog(FileListModel *fileListModel, AudioFileModel *metaInfo, SettingsModel *settings, QWidget *parent)
69 //Init the dialog, from the .ui file
71 setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint);
74 label_versionInfo->setText(QString().sprintf("v%d.%02d %s (Build %d)", lamexp_version_major(), lamexp_version_minor(), lamexp_version_release(), lamexp_version_build()));
75 label_versionInfo->installEventFilter(this);
78 qRegisterMetaType<QUuid>("QUuid");
80 //Center window in screen
81 QRect desktopRect = QApplication::desktop()->screenGeometry();
82 QRect thisRect = this->geometry();
83 move((desktopRect.width() - thisRect.width()) / 2, (desktopRect.height() - thisRect.height()) / 2);
84 setMinimumSize(thisRect.width(), thisRect.height());
87 connect(button_AbortProcess, SIGNAL(clicked()), this, SLOT(abortEncoding()));
89 //Init progress indicator
90 m_progressIndicator = new QMovie(":/images/Working.gif");
91 label_headerWorking->setMovie(m_progressIndicator);
92 progressBar->setValue(0);
95 m_progressModel = new ProgressModel();
96 view_log->setModel(m_progressModel);
97 view_log->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
98 view_log->verticalHeader()->hide();
99 view_log->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);
100 view_log->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
101 connect(m_progressModel, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(progressModelChanged()));
102 connect(m_progressModel, SIGNAL(modelReset()), this, SLOT(progressModelChanged()));
103 connect(view_log, SIGNAL(activated(QModelIndex)), this, SLOT(logViewDoubleClicked(QModelIndex)));
105 //Create context menu
106 m_contextMenu = new QMenu();
107 QAction *contextMenuAction = m_contextMenu->addAction(QIcon(":/icons/zoom.png"), "Show details for selected job");
108 view_log->setContextMenuPolicy(Qt::CustomContextMenu);
109 connect(view_log, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenuTriggered(QPoint)));
110 connect(contextMenuAction, SIGNAL(triggered(bool)), this, SLOT(contextMenuActionTriggered()));
115 for(int i = 0; i < fileListModel->rowCount(); i++)
117 m_pendingJobs.append(fileListModel->getFile(fileListModel->index(i,0)));
122 m_runningThreads = 0;
124 m_succeededFiles = 0;
126 m_userAborted = false;
129 ////////////////////////////////////////////////////////////
131 ////////////////////////////////////////////////////////////
133 ProcessingDialog::~ProcessingDialog(void)
135 view_log->setModel(NULL);
136 if(m_progressIndicator) m_progressIndicator->stop();
137 LAMEXP_DELETE(m_progressIndicator);
138 LAMEXP_DELETE(m_progressModel);
139 LAMEXP_DELETE(m_contextMenu);
141 WinSevenTaskbar::setOverlayIcon(this, NULL);
142 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNoState);
144 while(!m_threadList.isEmpty())
146 ProcessThread *thread = m_threadList.takeFirst();
153 ////////////////////////////////////////////////////////////
155 ////////////////////////////////////////////////////////////
157 void ProcessingDialog::showEvent(QShowEvent *event)
159 setCloseButtonEnabled(false);
160 button_closeDialog->setEnabled(false);
161 button_AbortProcess->setEnabled(false);
163 if(!SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS))
165 SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
168 QTimer::singleShot(1000, this, SLOT(initEncoding()));
171 void ProcessingDialog::closeEvent(QCloseEvent *event)
173 if(!button_closeDialog->isEnabled()) event->ignore();
176 bool ProcessingDialog::eventFilter(QObject *obj, QEvent *event)
178 static QColor defaultColor = QColor();
180 if(obj == label_versionInfo)
182 if(event->type() == QEvent::Enter)
184 QPalette palette = label_versionInfo->palette();
185 defaultColor = palette.color(QPalette::Normal, QPalette::WindowText);
186 palette.setColor(QPalette::Normal, QPalette::WindowText, Qt::red);
187 label_versionInfo->setPalette(palette);
189 else if(event->type() == QEvent::Leave)
191 QPalette palette = label_versionInfo->palette();
192 palette.setColor(QPalette::Normal, QPalette::WindowText, defaultColor);
193 label_versionInfo->setPalette(palette);
195 else if(event->type() == QEvent::MouseButtonPress)
197 QUrl url("http://mulder.dummwiedeutsch.de/");
198 QDesktopServices::openUrl(url);
205 ////////////////////////////////////////////////////////////
207 ////////////////////////////////////////////////////////////
209 void ProcessingDialog::initEncoding(void)
211 m_runningThreads = 0;
213 m_succeededFiles = 0;
215 m_userAborted = false;
218 CHANGE_BACKGROUND_COLOR(frame_header, QColor(Qt::white));
219 label_progress->setText("Encoding files, please wait...");
220 m_progressIndicator->start();
222 button_closeDialog->setEnabled(false);
223 button_AbortProcess->setEnabled(true);
224 progressBar->setRange(0, m_pendingJobs.count());
226 WinSevenTaskbar::initTaskbar();
227 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
228 WinSevenTaskbar::setTaskbarProgress(this, 0, m_pendingJobs.count());
229 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/control_play_blue.png"));
231 lamexp_cpu_t cpuFeatures = lamexp_detect_cpu_features();
233 for(int i = 0; i < min(max(cpuFeatures.count, 1), 4); i++)
239 void ProcessingDialog::abortEncoding(void)
241 m_userAborted = true;
242 button_AbortProcess->setEnabled(false);
244 label_progress->setText("Aborted! Waiting for running jobs to terminate...");
246 for(int i = 0; i < m_threadList.count(); i++)
248 m_threadList.at(i)->abort();
252 void ProcessingDialog::doneEncoding(void)
255 progressBar->setValue(progressBar->value() + 1);
259 label_progress->setText(QString("Encoding: %1 files of %2 completed so far, please wait...").arg(QString::number(progressBar->value()), QString::number(progressBar->maximum())));
260 WinSevenTaskbar::setTaskbarProgress(this, progressBar->value(), progressBar->maximum());
263 int index = m_threadList.indexOf(dynamic_cast<ProcessThread*>(QWidget::sender()));
266 m_threadList.takeAt(index)->deleteLater();
269 if(!m_pendingJobs.isEmpty() && !m_userAborted)
272 qDebug("Running jobs: %u", m_runningThreads);
276 if(m_runningThreads > 0)
278 qDebug("Running jobs: %u", m_runningThreads);
282 QApplication::setOverrideCursor(Qt::WaitCursor);
283 qDebug("Running jobs: %u", m_runningThreads);
285 if(!m_userAborted && m_settings->createPlaylist() && !m_settings->outputToSourceDir())
287 label_progress->setText("Creatig the playlist file, please wait...");
288 QApplication::processEvents();
294 CHANGE_BACKGROUND_COLOR(frame_header, QColor("#FFF3BA"));
295 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
296 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/error.png"));
297 label_progress->setText((m_succeededFiles > 0) ? QString("Process was aborted by the user after %1 file(s)!").arg(QString::number(m_succeededFiles)) : "Process was aborted prematurely by the user!");
298 QApplication::processEvents();
299 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ABORTED), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
305 CHANGE_BACKGROUND_COLOR(frame_header, QColor("#FFBABA"));
306 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
307 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/exclamation.png"));
308 label_progress->setText(QString("Error: %1 of %2 files failed. Double-click failed items for detailed information!").arg(QString::number(m_failedFiles), QString::number(m_failedFiles + m_succeededFiles)));
309 QApplication::processEvents();
310 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
314 CHANGE_BACKGROUND_COLOR(frame_header, QColor("#D1FFD5"));
315 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
316 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/accept.png"));
317 label_progress->setText("Alle files completed successfully.");
318 QApplication::processEvents();
319 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_SUCCESS), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
323 setCloseButtonEnabled(true);
324 button_closeDialog->setEnabled(true);
325 button_AbortProcess->setEnabled(false);
327 view_log->scrollToBottom();
328 m_progressIndicator->stop();
329 progressBar->setValue(progressBar->maximum());
330 WinSevenTaskbar::setTaskbarProgress(this, progressBar->value(), progressBar->maximum());
332 QApplication::restoreOverrideCursor();
335 void ProcessingDialog::processFinished(const QUuid &jobId, const QString &outFileName, bool success)
340 m_playList.append(outFileName);
348 void ProcessingDialog::progressModelChanged(void)
350 view_log->scrollToBottom();
353 void ProcessingDialog::logViewDoubleClicked(const QModelIndex &index)
355 if(m_runningThreads == 0)
357 const QStringList &logFile = m_progressModel->getLogFile(index);
358 LogViewDialog *logView = new LogViewDialog(this);
359 logView->setWindowTitle(QString("LameXP - [%1]").arg(m_progressModel->data(index, Qt::DisplayRole).toString()));
360 logView->exec(logFile);
361 LAMEXP_DELETE(logView);
365 MessageBeep(MB_ICONWARNING);
369 void ProcessingDialog::contextMenuTriggered(const QPoint &pos)
371 m_contextMenu->popup(view_log->mapToGlobal(pos));
374 void ProcessingDialog::contextMenuActionTriggered(void)
376 QModelIndex index = view_log->indexAt(view_log->mapFromGlobal(m_contextMenu->pos()));
377 logViewDoubleClicked(index.isValid() ? index : view_log->currentIndex());
380 ////////////////////////////////////////////////////////////
382 ////////////////////////////////////////////////////////////
384 void ProcessingDialog::startNextJob(void)
386 if(m_pendingJobs.isEmpty())
392 AudioFileModel currentFile = updateMetaInfo(m_pendingJobs.takeFirst());
393 AbstractEncoder *encoder = NULL;
395 switch(m_settings->compressionEncoder())
397 case SettingsModel::MP3Encoder:
399 MP3Encoder *mp3Encoder = new MP3Encoder();
400 mp3Encoder->setBitrate(m_settings->compressionBitrate());
401 mp3Encoder->setRCMode(m_settings->compressionRCMode());
402 encoder = mp3Encoder;
405 case SettingsModel::VorbisEncoder:
407 VorbisEncoder *vorbisEncoder = new VorbisEncoder();
408 vorbisEncoder->setBitrate(m_settings->compressionBitrate());
409 vorbisEncoder->setRCMode(m_settings->compressionRCMode());
410 encoder = vorbisEncoder;
413 case SettingsModel::AACEncoder:
415 AACEncoder *aacEncoder = new AACEncoder();
416 aacEncoder->setBitrate(m_settings->compressionBitrate());
417 aacEncoder->setRCMode(m_settings->compressionRCMode());
418 encoder = aacEncoder;
422 throw "Unsupported encoder!";
425 ProcessThread *thread = new ProcessThread(currentFile, (m_settings->outputToSourceDir() ? QFileInfo(currentFile.filePath()).absolutePath(): m_settings->outputDir()), encoder);
426 m_threadList.append(thread);
428 connect(thread, SIGNAL(finished()), this, SLOT(doneEncoding()), Qt::QueuedConnection);
429 connect(thread, SIGNAL(processStateInitialized(QUuid,QString,QString,int)), m_progressModel, SLOT(addJob(QUuid,QString,QString,int)), Qt::QueuedConnection);
430 connect(thread, SIGNAL(processStateChanged(QUuid,QString,int)), m_progressModel, SLOT(updateJob(QUuid,QString,int)), Qt::QueuedConnection);
431 connect(thread, SIGNAL(processStateFinished(QUuid,QString,bool)), this, SLOT(processFinished(QUuid,QString,bool)), Qt::QueuedConnection);
432 connect(thread, SIGNAL(processMessageLogged(QUuid,QString)), m_progressModel, SLOT(appendToLog(QUuid,QString)), Qt::QueuedConnection);
438 void ProcessingDialog::writePlayList(void)
440 QString playListName = (m_metaInfo->fileAlbum().isEmpty() ? "Playlist" : m_metaInfo->fileAlbum());
442 const static char *invalidChars = "\\/:*?\"<>|";
443 for(int i = 0; invalidChars[i]; i++)
445 playListName.replace(invalidChars[i], ' ');
446 playListName = playListName.simplified();
449 QString playListFile = QString("%1/%2.m3u").arg(m_settings->outputDir(), playListName);
452 while(QFileInfo(playListFile).exists())
454 playListFile = QString("%1/%2 (%3).m3u").arg(m_settings->outputDir(), playListName, QString::number(++counter));
457 QFile playList(playListFile);
458 if(playList.open(QIODevice::WriteOnly))
460 playList.write("#EXTM3U\r\n");
461 for(int i = 0; i < m_playList.count(); i++)
463 playList.write(QFileInfo(m_playList.at(i)).fileName().toUtf8().constData());
464 playList.write("\r\n");
470 QMessageBox::warning(this, "Playlist creation failed", QString("The playlist file could not be created:<br><nobr>%1</nobr>").arg(playListFile));
474 AudioFileModel ProcessingDialog::updateMetaInfo(const AudioFileModel &audioFile)
476 if(!m_settings->writeMetaTags())
478 return AudioFileModel(audioFile.filePath());
481 AudioFileModel result = audioFile;
483 if(!m_metaInfo->fileArtist().isEmpty()) result.setFileArtist(m_metaInfo->fileArtist());
484 if(!m_metaInfo->fileAlbum().isEmpty()) result.setFileAlbum(m_metaInfo->fileAlbum());
485 if(!m_metaInfo->fileGenre().isEmpty()) result.setFileGenre(m_metaInfo->fileGenre());
486 if(m_metaInfo->fileYear()) result.setFileYear(m_metaInfo->fileYear());
487 if(m_metaInfo->filePosition()) result.setFileYear(m_metaInfo->filePosition() != UINT_MAX ? m_metaInfo->filePosition() : m_currentFile);
488 if(!m_metaInfo->fileComment().isEmpty()) result.setFileComment(m_metaInfo->fileComment());
493 void ProcessingDialog::setCloseButtonEnabled(bool enabled)
495 HMENU hMenu = GetSystemMenu((HWND) winId(), FALSE);
496 EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | (enabled ? MF_ENABLED : MF_GRAYED));