OSDN Git Service

Added support for Windows 7 taskbar features (progress and overlay icons).
[lamexp/LameXP.git] / src / Dialog_Processing.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2010 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
22 #include "Dialog_Processing.h"
23
24 #include "Global.h"
25 #include "Resource.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"
35
36 #include <QApplication>
37 #include <QRect>
38 #include <QDesktopWidget>
39 #include <QMovie>
40 #include <QMessageBox>
41 #include <QTimer>
42 #include <QCloseEvent>
43 #include <QDesktopServices>
44 #include <QUrl>
45 #include <QUuid>
46 #include <QFileInfo>
47 #include <QDir>
48 #include <QMenu>
49
50 #include <Windows.h>
51
52 #define CHANGE_BACKGROUND_COLOR(WIDGET, COLOR) \
53 { \
54         QPalette palette = WIDGET->palette(); \
55         palette.setColor(QPalette::Background, COLOR); \
56         WIDGET->setPalette(palette); \
57 }
58
59 ////////////////////////////////////////////////////////////
60 // Constructor
61 ////////////////////////////////////////////////////////////
62
63 ProcessingDialog::ProcessingDialog(FileListModel *fileListModel, AudioFileModel *metaInfo, SettingsModel *settings, QWidget *parent)
64 :
65         QDialog(parent),
66         m_settings(settings),
67         m_metaInfo(metaInfo)
68 {
69         //Init the dialog, from the .ui file
70         setupUi(this);
71         setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint);
72         
73         //Setup version info
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);
76
77         //Register meta type
78         qRegisterMetaType<QUuid>("QUuid");
79
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());
85
86         //Enable buttons
87         connect(button_AbortProcess, SIGNAL(clicked()), this, SLOT(abortEncoding()));
88         
89         //Init progress indicator
90         m_progressIndicator = new QMovie(":/images/Working.gif");
91         label_headerWorking->setMovie(m_progressIndicator);
92         progressBar->setValue(0);
93
94         //Init progress model
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)));
104
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()));
111         
112         //Enque jobs
113         if(fileListModel)
114         {
115                 for(int i = 0; i < fileListModel->rowCount(); i++)
116                 {
117                         m_pendingJobs.append(fileListModel->getFile(fileListModel->index(i,0)));
118                 }
119         }
120
121         //Init other vars
122         m_runningThreads = 0;
123         m_currentFile = 0;
124         m_succeededFiles = 0;
125         m_failedFiles = 0;
126         m_userAborted = false;
127 }
128
129 ////////////////////////////////////////////////////////////
130 // Destructor
131 ////////////////////////////////////////////////////////////
132
133 ProcessingDialog::~ProcessingDialog(void)
134 {
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);
140
141         WinSevenTaskbar::setOverlayIcon(this, NULL);
142         WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNoState);
143
144         while(!m_threadList.isEmpty())
145         {
146                 ProcessThread *thread = m_threadList.takeFirst();
147                 thread->terminate();
148                 thread->wait(15000);
149                 delete thread;
150         }
151 }
152
153 ////////////////////////////////////////////////////////////
154 // EVENTS
155 ////////////////////////////////////////////////////////////
156
157 void ProcessingDialog::showEvent(QShowEvent *event)
158 {
159         setCloseButtonEnabled(false);
160         button_closeDialog->setEnabled(false);
161         button_AbortProcess->setEnabled(false);
162
163         if(!SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS))
164         {
165                 SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
166         }
167
168         QTimer::singleShot(1000, this, SLOT(initEncoding()));
169 }
170
171 void ProcessingDialog::closeEvent(QCloseEvent *event)
172 {
173         if(!button_closeDialog->isEnabled()) event->ignore();
174 }
175
176 bool ProcessingDialog::eventFilter(QObject *obj, QEvent *event)
177 {
178         static QColor defaultColor = QColor();
179
180         if(obj == label_versionInfo)
181         {
182                 if(event->type() == QEvent::Enter)
183                 {
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);
188                 }
189                 else if(event->type() == QEvent::Leave)
190                 {
191                         QPalette palette = label_versionInfo->palette();
192                         palette.setColor(QPalette::Normal, QPalette::WindowText, defaultColor);
193                         label_versionInfo->setPalette(palette);
194                 }
195                 else if(event->type() == QEvent::MouseButtonPress)
196                 {
197                         QUrl url("http://mulder.dummwiedeutsch.de/");
198                         QDesktopServices::openUrl(url);
199                 }
200         }
201
202         return false;
203 }
204
205 ////////////////////////////////////////////////////////////
206 // SLOTS
207 ////////////////////////////////////////////////////////////
208
209 void ProcessingDialog::initEncoding(void)
210 {
211         m_runningThreads = 0;
212         m_currentFile = 0;
213         m_succeededFiles = 0;
214         m_failedFiles = 0;
215         m_userAborted = false;
216         m_playList.clear();
217         
218         CHANGE_BACKGROUND_COLOR(frame_header, QColor(Qt::white));
219         label_progress->setText("Encoding files, please wait...");
220         m_progressIndicator->start();
221         
222         button_closeDialog->setEnabled(false);
223         button_AbortProcess->setEnabled(true);
224         progressBar->setRange(0, m_pendingJobs.count());
225
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"));
230
231         lamexp_cpu_t cpuFeatures = lamexp_detect_cpu_features();
232
233         for(int i = 0; i < min(max(cpuFeatures.count, 1), 4); i++)
234         {
235                 startNextJob();
236         }
237 }
238
239 void ProcessingDialog::abortEncoding(void)
240 {
241         m_userAborted = true;
242         button_AbortProcess->setEnabled(false);
243         
244         label_progress->setText("Aborted! Waiting for running jobs to terminate...");
245
246         for(int i = 0; i < m_threadList.count(); i++)
247         {
248                 m_threadList.at(i)->abort();
249         }
250 }
251
252 void ProcessingDialog::doneEncoding(void)
253 {
254         m_runningThreads--;
255         progressBar->setValue(progressBar->value() + 1);
256         
257         if(!m_userAborted)
258         {
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());
261         }
262         
263         int index = m_threadList.indexOf(dynamic_cast<ProcessThread*>(QWidget::sender()));
264         if(index >= 0)
265         {
266                 m_threadList.takeAt(index)->deleteLater();
267         }
268
269         if(!m_pendingJobs.isEmpty() && !m_userAborted)
270         {
271                 startNextJob();
272                 qDebug("Running jobs: %u", m_runningThreads);
273                 return;
274         }
275         
276         if(m_runningThreads > 0)
277         {
278                 qDebug("Running jobs: %u", m_runningThreads);
279                 return;
280         }
281
282         QApplication::setOverrideCursor(Qt::WaitCursor);
283         qDebug("Running jobs: %u", m_runningThreads);
284
285         if(!m_userAborted && m_settings->createPlaylist() && !m_settings->outputToSourceDir())
286         {
287                 label_progress->setText("Creatig the playlist file, please wait...");
288                 QApplication::processEvents();
289                 writePlayList();
290         }
291         
292         if(m_userAborted)
293         {
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);
300         }
301         else
302         {
303                 if(m_failedFiles)
304                 {
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);
311                 }
312                 else
313                 {
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);
320                 }
321         }
322         
323         setCloseButtonEnabled(true);
324         button_closeDialog->setEnabled(true);
325         button_AbortProcess->setEnabled(false);
326
327         view_log->scrollToBottom();
328         m_progressIndicator->stop();
329         progressBar->setValue(progressBar->maximum());
330         WinSevenTaskbar::setTaskbarProgress(this, progressBar->value(), progressBar->maximum());
331
332         QApplication::restoreOverrideCursor();
333 }
334
335 void ProcessingDialog::processFinished(const QUuid &jobId, const QString &outFileName, bool success)
336 {
337         if(success)
338         {
339                 m_succeededFiles++;
340                 m_playList.append(outFileName);
341         }
342         else
343         {
344                 m_failedFiles++;
345         }
346 }
347
348 void ProcessingDialog::progressModelChanged(void)
349 {
350         view_log->scrollToBottom();
351 }
352
353 void ProcessingDialog::logViewDoubleClicked(const QModelIndex &index)
354 {
355         if(m_runningThreads == 0)
356         {
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);
362         }
363         else
364         {
365                 MessageBeep(MB_ICONWARNING);
366         }
367 }
368
369 void ProcessingDialog::contextMenuTriggered(const QPoint &pos)
370 {
371         m_contextMenu->popup(view_log->mapToGlobal(pos));
372 }
373
374 void ProcessingDialog::contextMenuActionTriggered(void)
375 {
376         QModelIndex index = view_log->indexAt(view_log->mapFromGlobal(m_contextMenu->pos()));
377         logViewDoubleClicked(index.isValid() ? index : view_log->currentIndex());
378 }
379
380 ////////////////////////////////////////////////////////////
381 // Private Functions
382 ////////////////////////////////////////////////////////////
383
384 void ProcessingDialog::startNextJob(void)
385 {
386         if(m_pendingJobs.isEmpty())
387         {
388                 return;
389         }
390         
391         m_currentFile++;
392         AudioFileModel currentFile = updateMetaInfo(m_pendingJobs.takeFirst());
393         AbstractEncoder *encoder = NULL;
394         
395         switch(m_settings->compressionEncoder())
396         {
397         case SettingsModel::MP3Encoder:
398                 {
399                         MP3Encoder *mp3Encoder = new MP3Encoder();
400                         mp3Encoder->setBitrate(m_settings->compressionBitrate());
401                         mp3Encoder->setRCMode(m_settings->compressionRCMode());
402                         encoder = mp3Encoder;
403                 }
404                 break;
405         case SettingsModel::VorbisEncoder:
406                 {
407                         VorbisEncoder *vorbisEncoder = new VorbisEncoder();
408                         vorbisEncoder->setBitrate(m_settings->compressionBitrate());
409                         vorbisEncoder->setRCMode(m_settings->compressionRCMode());
410                         encoder = vorbisEncoder;
411                 }
412                 break;
413         case SettingsModel::AACEncoder:
414                 {
415                         AACEncoder *aacEncoder = new AACEncoder();
416                         aacEncoder->setBitrate(m_settings->compressionBitrate());
417                         aacEncoder->setRCMode(m_settings->compressionRCMode());
418                         encoder = aacEncoder;
419                 }
420                 break;
421         default:
422                 throw "Unsupported encoder!";
423         }
424
425         ProcessThread *thread = new ProcessThread(currentFile, (m_settings->outputToSourceDir() ? QFileInfo(currentFile.filePath()).absolutePath(): m_settings->outputDir()), encoder);
426         m_threadList.append(thread);
427         
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);
433         
434         m_runningThreads++;
435         thread->start();
436 }
437
438 void ProcessingDialog::writePlayList(void)
439 {
440         QString playListName = (m_metaInfo->fileAlbum().isEmpty() ? "Playlist" : m_metaInfo->fileAlbum());
441
442         const static char *invalidChars = "\\/:*?\"<>|";
443         for(int i = 0; invalidChars[i]; i++)
444         {
445                 playListName.replace(invalidChars[i], ' ');
446                 playListName = playListName.simplified();
447         }
448         
449         QString playListFile = QString("%1/%2.m3u").arg(m_settings->outputDir(), playListName);
450
451         int counter = 1;
452         while(QFileInfo(playListFile).exists())
453         {
454                 playListFile = QString("%1/%2 (%3).m3u").arg(m_settings->outputDir(), playListName, QString::number(++counter));
455         }
456         
457         QFile playList(playListFile);
458         if(playList.open(QIODevice::WriteOnly))
459         {
460                 playList.write("#EXTM3U\r\n");
461                 for(int i = 0; i < m_playList.count(); i++)
462                 {
463                         playList.write(QFileInfo(m_playList.at(i)).fileName().toUtf8().constData());
464                         playList.write("\r\n");
465                 }
466                 playList.close();
467         }
468         else
469         {
470                 QMessageBox::warning(this, "Playlist creation failed", QString("The playlist file could not be created:<br><nobr>%1</nobr>").arg(playListFile));
471         }
472 }
473
474 AudioFileModel ProcessingDialog::updateMetaInfo(const AudioFileModel &audioFile)
475 {
476         if(!m_settings->writeMetaTags())
477         {
478                 return AudioFileModel(audioFile.filePath());
479         }
480         
481         AudioFileModel result = audioFile;
482
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());
489
490         return result;
491 }
492
493 void ProcessingDialog::setCloseButtonEnabled(bool enabled)
494 {
495         HMENU hMenu = GetSystemMenu((HWND) winId(), FALSE);
496         EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | (enabled ? MF_ENABLED : MF_GRAYED));
497 }