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>
49 #include <QSystemTrayIcon>
53 #define CHANGE_BACKGROUND_COLOR(WIDGET, COLOR) \
55 QPalette palette = WIDGET->palette(); \
56 palette.setColor(QPalette::Background, COLOR); \
57 WIDGET->setPalette(palette); \
60 #define SET_PROGRESS_TEXT(TXT) \
62 label_progress->setText(TXT); \
63 m_systemTray->setToolTip(QString().sprintf("LameXP v%d.%02d\n%ls", lamexp_version_major(), lamexp_version_minor(), QString(TXT).utf16())); \
66 ////////////////////////////////////////////////////////////
68 ////////////////////////////////////////////////////////////
70 ProcessingDialog::ProcessingDialog(FileListModel
*fileListModel
, AudioFileModel
*metaInfo
, SettingsModel
*settings
, QWidget
*parent
)
73 m_systemTray(new QSystemTrayIcon(QIcon(":/icons/cd.png"), this)),
77 //Init the dialog, from the .ui file
79 setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint
);
82 label_versionInfo
->setText(QString().sprintf("v%d.%02d %s (Build %d)", lamexp_version_major(), lamexp_version_minor(), lamexp_version_release(), lamexp_version_build()));
83 label_versionInfo
->installEventFilter(this);
86 qRegisterMetaType
<QUuid
>("QUuid");
88 //Center window in screen
89 QRect desktopRect
= QApplication::desktop()->screenGeometry();
90 QRect thisRect
= this->geometry();
91 move((desktopRect
.width() - thisRect
.width()) / 2, (desktopRect
.height() - thisRect
.height()) / 2);
92 setMinimumSize(thisRect
.width(), thisRect
.height());
95 connect(button_AbortProcess
, SIGNAL(clicked()), this, SLOT(abortEncoding()));
97 //Init progress indicator
98 m_progressIndicator
= new QMovie(":/images/Working.gif");
99 label_headerWorking
->setMovie(m_progressIndicator
);
100 progressBar
->setValue(0);
102 //Init progress model
103 m_progressModel
= new ProgressModel();
104 view_log
->setModel(m_progressModel
);
105 view_log
->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents
);
106 view_log
->verticalHeader()->hide();
107 view_log
->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents
);
108 view_log
->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch
);
109 connect(m_progressModel
, SIGNAL(rowsInserted(QModelIndex
,int,int)), this, SLOT(progressModelChanged()));
110 connect(m_progressModel
, SIGNAL(modelReset()), this, SLOT(progressModelChanged()));
111 connect(view_log
, SIGNAL(activated(QModelIndex
)), this, SLOT(logViewDoubleClicked(QModelIndex
)));
113 //Create context menu
114 m_contextMenu
= new QMenu();
115 QAction
*contextMenuAction
= m_contextMenu
->addAction(QIcon(":/icons/zoom.png"), "Show details for selected job");
116 view_log
->setContextMenuPolicy(Qt::CustomContextMenu
);
117 connect(view_log
, SIGNAL(customContextMenuRequested(QPoint
)), this, SLOT(contextMenuTriggered(QPoint
)));
118 connect(contextMenuAction
, SIGNAL(triggered(bool)), this, SLOT(contextMenuActionTriggered()));
123 for(int i
= 0; i
< fileListModel
->rowCount(); i
++)
125 m_pendingJobs
.append(fileListModel
->getFile(fileListModel
->index(i
,0)));
129 //Enable system tray icon
130 connect(m_systemTray
, SIGNAL(activated(QSystemTrayIcon::ActivationReason
)), this, SLOT(systemTrayActivated(QSystemTrayIcon::ActivationReason
)));
133 m_runningThreads
= 0;
136 m_succeededJobs
.clear();
137 m_failedJobs
.clear();
138 m_userAborted
= false;
141 ////////////////////////////////////////////////////////////
143 ////////////////////////////////////////////////////////////
145 ProcessingDialog::~ProcessingDialog(void)
147 view_log
->setModel(NULL
);
148 if(m_progressIndicator
) m_progressIndicator
->stop();
149 LAMEXP_DELETE(m_progressIndicator
);
150 LAMEXP_DELETE(m_progressModel
);
151 LAMEXP_DELETE(m_contextMenu
);
152 LAMEXP_DELETE(m_systemTray
);
154 WinSevenTaskbar::setOverlayIcon(this, NULL
);
155 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNoState
);
157 while(!m_threadList
.isEmpty())
159 ProcessThread
*thread
= m_threadList
.takeFirst();
166 ////////////////////////////////////////////////////////////
168 ////////////////////////////////////////////////////////////
170 void ProcessingDialog::showEvent(QShowEvent
*event
)
172 setCloseButtonEnabled(false);
173 button_closeDialog
->setEnabled(false);
174 button_AbortProcess
->setEnabled(false);
175 m_systemTray
->setVisible(true);
177 if(!SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS
))
179 SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS
);
182 QTimer::singleShot(1000, this, SLOT(initEncoding()));
185 void ProcessingDialog::closeEvent(QCloseEvent
*event
)
187 if(!button_closeDialog
->isEnabled())
193 m_systemTray
->setVisible(false);
197 bool ProcessingDialog::eventFilter(QObject
*obj
, QEvent
*event
)
199 static QColor defaultColor
= QColor();
201 if(obj
== label_versionInfo
)
203 if(event
->type() == QEvent::Enter
)
205 QPalette palette
= label_versionInfo
->palette();
206 defaultColor
= palette
.color(QPalette::Normal
, QPalette::WindowText
);
207 palette
.setColor(QPalette::Normal
, QPalette::WindowText
, Qt::red
);
208 label_versionInfo
->setPalette(palette
);
210 else if(event
->type() == QEvent::Leave
)
212 QPalette palette
= label_versionInfo
->palette();
213 palette
.setColor(QPalette::Normal
, QPalette::WindowText
, defaultColor
);
214 label_versionInfo
->setPalette(palette
);
216 else if(event
->type() == QEvent::MouseButtonPress
)
218 QUrl
url("http://mulder.dummwiedeutsch.de/");
219 QDesktopServices::openUrl(url
);
226 ////////////////////////////////////////////////////////////
228 ////////////////////////////////////////////////////////////
230 void ProcessingDialog::initEncoding(void)
232 m_runningThreads
= 0;
235 m_succeededJobs
.clear();
236 m_failedJobs
.clear();
237 m_userAborted
= false;
240 CHANGE_BACKGROUND_COLOR(frame_header
, QColor(Qt::white
));
241 SET_PROGRESS_TEXT("Encoding files, please wait...");
242 m_progressIndicator
->start();
244 button_closeDialog
->setEnabled(false);
245 button_AbortProcess
->setEnabled(true);
246 progressBar
->setRange(0, m_pendingJobs
.count());
248 WinSevenTaskbar::initTaskbar();
249 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState
);
250 WinSevenTaskbar::setTaskbarProgress(this, 0, m_pendingJobs
.count());
251 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/control_play_blue.png"));
253 lamexp_cpu_t cpuFeatures
= lamexp_detect_cpu_features();
255 for(int i
= 0; i
< min(max(cpuFeatures
.count
, 1), 4); i
++)
261 void ProcessingDialog::abortEncoding(void)
263 m_userAborted
= true;
264 button_AbortProcess
->setEnabled(false);
266 SET_PROGRESS_TEXT("Aborted! Waiting for running jobs to terminate...");
268 for(int i
= 0; i
< m_threadList
.count(); i
++)
270 m_threadList
.at(i
)->abort();
274 void ProcessingDialog::doneEncoding(void)
277 progressBar
->setValue(progressBar
->value() + 1);
281 SET_PROGRESS_TEXT(QString("Encoding: %1 files of %2 completed so far, please wait...").arg(QString::number(progressBar
->value()), QString::number(progressBar
->maximum())));
282 WinSevenTaskbar::setTaskbarProgress(this, progressBar
->value(), progressBar
->maximum());
285 int index
= m_threadList
.indexOf(dynamic_cast<ProcessThread
*>(QWidget::sender()));
288 m_threadList
.takeAt(index
)->deleteLater();
291 if(!m_pendingJobs
.isEmpty() && !m_userAborted
)
294 qDebug("Running jobs: %u", m_runningThreads
);
298 if(m_runningThreads
> 0)
300 qDebug("Running jobs: %u", m_runningThreads
);
304 QApplication::setOverrideCursor(Qt::WaitCursor
);
305 qDebug("Running jobs: %u", m_runningThreads
);
307 if(!m_userAborted
&& m_settings
->createPlaylist() && !m_settings
->outputToSourceDir())
309 SET_PROGRESS_TEXT("Creatig the playlist file, please wait...");
310 QApplication::processEvents();
316 CHANGE_BACKGROUND_COLOR(frame_header
, QColor("#FFF3BA"));
317 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState
);
318 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/error.png"));
319 SET_PROGRESS_TEXT((m_succeededJobs
.count() > 0) ? QString("Process was aborted by the user after %1 file(s)!").arg(QString::number(m_succeededJobs
.count())) : "Process was aborted prematurely by the user!");
320 m_systemTray
->showMessage("LameXP - Aborted", "Process was aborted by the user.", QSystemTrayIcon::Warning
);
321 QApplication::processEvents();
322 if(m_settings
->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ABORTED
), GetModuleHandle(NULL
), SND_RESOURCE
| SND_SYNC
);
326 if(m_failedJobs
.count() > 0)
328 CHANGE_BACKGROUND_COLOR(frame_header
, QColor("#FFBABA"));
329 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState
);
330 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/exclamation.png"));
331 SET_PROGRESS_TEXT(QString("Error: %1 of %2 files failed. Double-click failed items for detailed information!").arg(QString::number(m_failedJobs
.count()), QString::number(m_failedJobs
.count() + m_succeededJobs
.count())));
332 m_systemTray
->showMessage("LameXP - Error", "At least one file has failed!", QSystemTrayIcon::Critical
);
333 QApplication::processEvents();
334 if(m_settings
->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR
), GetModuleHandle(NULL
), SND_RESOURCE
| SND_SYNC
);
338 CHANGE_BACKGROUND_COLOR(frame_header
, QColor("#D1FFD5"));
339 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState
);
340 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/accept.png"));
341 SET_PROGRESS_TEXT("Alle files completed successfully.");
342 m_systemTray
->showMessage("LameXP - Done", "All files completed successfully.", QSystemTrayIcon::Information
);
343 QApplication::processEvents();
344 if(m_settings
->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_SUCCESS
), GetModuleHandle(NULL
), SND_RESOURCE
| SND_SYNC
);
348 setCloseButtonEnabled(true);
349 button_closeDialog
->setEnabled(true);
350 button_AbortProcess
->setEnabled(false);
352 view_log
->scrollToBottom();
353 m_progressIndicator
->stop();
354 progressBar
->setValue(progressBar
->maximum());
355 WinSevenTaskbar::setTaskbarProgress(this, progressBar
->value(), progressBar
->maximum());
357 QApplication::restoreOverrideCursor();
360 void ProcessingDialog::processFinished(const QUuid
&jobId
, const QString
&outFileName
, bool success
)
364 m_playList
.insert(jobId
, outFileName
);
365 m_succeededJobs
.append(jobId
);
369 m_failedJobs
.append(jobId
);
373 void ProcessingDialog::progressModelChanged(void)
375 view_log
->scrollToBottom();
378 void ProcessingDialog::logViewDoubleClicked(const QModelIndex
&index
)
380 if(m_runningThreads
== 0)
382 const QStringList
&logFile
= m_progressModel
->getLogFile(index
);
383 LogViewDialog
*logView
= new LogViewDialog(this);
384 logView
->setWindowTitle(QString("LameXP - [%1]").arg(m_progressModel
->data(index
, Qt::DisplayRole
).toString()));
385 logView
->exec(logFile
);
386 LAMEXP_DELETE(logView
);
390 MessageBeep(MB_ICONWARNING
);
394 void ProcessingDialog::contextMenuTriggered(const QPoint
&pos
)
396 m_contextMenu
->popup(view_log
->mapToGlobal(pos
));
399 void ProcessingDialog::contextMenuActionTriggered(void)
401 QModelIndex index
= view_log
->indexAt(view_log
->mapFromGlobal(m_contextMenu
->pos()));
402 logViewDoubleClicked(index
.isValid() ? index
: view_log
->currentIndex());
405 ////////////////////////////////////////////////////////////
407 ////////////////////////////////////////////////////////////
409 void ProcessingDialog::startNextJob(void)
411 if(m_pendingJobs
.isEmpty())
417 AudioFileModel currentFile
= updateMetaInfo(m_pendingJobs
.takeFirst());
418 AbstractEncoder
*encoder
= NULL
;
420 switch(m_settings
->compressionEncoder())
422 case SettingsModel::MP3Encoder
:
424 MP3Encoder
*mp3Encoder
= new MP3Encoder();
425 mp3Encoder
->setBitrate(m_settings
->compressionBitrate());
426 mp3Encoder
->setRCMode(m_settings
->compressionRCMode());
427 encoder
= mp3Encoder
;
430 case SettingsModel::VorbisEncoder
:
432 VorbisEncoder
*vorbisEncoder
= new VorbisEncoder();
433 vorbisEncoder
->setBitrate(m_settings
->compressionBitrate());
434 vorbisEncoder
->setRCMode(m_settings
->compressionRCMode());
435 encoder
= vorbisEncoder
;
438 case SettingsModel::AACEncoder
:
440 AACEncoder
*aacEncoder
= new AACEncoder();
441 aacEncoder
->setBitrate(m_settings
->compressionBitrate());
442 aacEncoder
->setRCMode(m_settings
->compressionRCMode());
443 encoder
= aacEncoder
;
447 throw "Unsupported encoder!";
450 ProcessThread
*thread
= new ProcessThread(currentFile
, (m_settings
->outputToSourceDir() ? QFileInfo(currentFile
.filePath()).absolutePath(): m_settings
->outputDir()), encoder
);
452 m_threadList
.append(thread
);
453 m_allJobs
.append(thread
->getId());
455 connect(thread
, SIGNAL(finished()), this, SLOT(doneEncoding()), Qt::QueuedConnection
);
456 connect(thread
, SIGNAL(processStateInitialized(QUuid
,QString
,QString
,int)), m_progressModel
, SLOT(addJob(QUuid
,QString
,QString
,int)), Qt::QueuedConnection
);
457 connect(thread
, SIGNAL(processStateChanged(QUuid
,QString
,int)), m_progressModel
, SLOT(updateJob(QUuid
,QString
,int)), Qt::QueuedConnection
);
458 connect(thread
, SIGNAL(processStateFinished(QUuid
,QString
,bool)), this, SLOT(processFinished(QUuid
,QString
,bool)), Qt::QueuedConnection
);
459 connect(thread
, SIGNAL(processMessageLogged(QUuid
,QString
)), m_progressModel
, SLOT(appendToLog(QUuid
,QString
)), Qt::QueuedConnection
);
465 void ProcessingDialog::writePlayList(void)
467 if(m_succeededJobs
.count() <= 0 || m_allJobs
.count() <= 0)
469 qWarning("WritePlayList: Nothing to do!");
473 QString playListName
= (m_metaInfo
->fileAlbum().isEmpty() ? "Playlist" : m_metaInfo
->fileAlbum());
475 const static char *invalidChars
= "\\/:*?\"<>|";
476 for(int i
= 0; invalidChars
[i
]; i
++)
478 playListName
.replace(invalidChars
[i
], ' ');
479 playListName
= playListName
.simplified();
482 QString playListFile
= QString("%1/%2.m3u").arg(m_settings
->outputDir(), playListName
);
485 while(QFileInfo(playListFile
).exists())
487 playListFile
= QString("%1/%2 (%3).m3u").arg(m_settings
->outputDir(), playListName
, QString::number(++counter
));
490 QFile
playList(playListFile
);
491 if(playList
.open(QIODevice::WriteOnly
))
493 playList
.write("#EXTM3U\r\n");
494 for(int i
= 0; i
< m_allJobs
.count(); i
++)
497 if(!m_succeededJobs
.contains(m_allJobs
.at(i
))) continue;
498 playList
.write(QFileInfo(m_playList
.value(m_allJobs
.at(i
), "N/A")).fileName().toUtf8().constData());
499 playList
.write("\r\n");
505 QMessageBox::warning(this, "Playlist creation failed", QString("The playlist file could not be created:<br><nobr>%1</nobr>").arg(playListFile
));
509 AudioFileModel
ProcessingDialog::updateMetaInfo(const AudioFileModel
&audioFile
)
511 if(!m_settings
->writeMetaTags())
513 return AudioFileModel(audioFile
.filePath());
516 AudioFileModel result
= audioFile
;
518 if(!m_metaInfo
->fileArtist().isEmpty()) result
.setFileArtist(m_metaInfo
->fileArtist());
519 if(!m_metaInfo
->fileAlbum().isEmpty()) result
.setFileAlbum(m_metaInfo
->fileAlbum());
520 if(!m_metaInfo
->fileGenre().isEmpty()) result
.setFileGenre(m_metaInfo
->fileGenre());
521 if(m_metaInfo
->fileYear()) result
.setFileYear(m_metaInfo
->fileYear());
522 if(m_metaInfo
->filePosition()) result
.setFileYear(m_metaInfo
->filePosition() != UINT_MAX
? m_metaInfo
->filePosition() : m_currentFile
);
523 if(!m_metaInfo
->fileComment().isEmpty()) result
.setFileComment(m_metaInfo
->fileComment());
528 void ProcessingDialog::setCloseButtonEnabled(bool enabled
)
530 HMENU hMenu
= GetSystemMenu((HWND
) winId(), FALSE
);
531 EnableMenuItem(hMenu
, SC_CLOSE
, MF_BYCOMMAND
| (enabled
? MF_ENABLED
: MF_GRAYED
));
534 void ProcessingDialog::systemTrayActivated(QSystemTrayIcon::ActivationReason reason
)
536 if(reason
== QSystemTrayIcon::DoubleClick
)
538 SetForegroundWindow(this->winId());