OSDN Git Service

Detect the entry points for some of the Win32 API functions on Runtime, so the execut...
[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 "Model_FileList.h"
26 #include "Model_Progress.h"
27 #include "Model_Settings.h"
28 #include "Thread_Process.h"
29 #include "Encoder_MP3.h"
30 #include "Dialog_LogView.h"
31
32 #include <QApplication>
33 #include <QRect>
34 #include <QDesktopWidget>
35 #include <QMovie>
36 #include <QMessageBox>
37 #include <QTimer>
38 #include <QCloseEvent>
39 #include <QDesktopServices>
40 #include <QUrl>
41 #include <QUuid>
42 #include <QFileInfo>
43 #include <QDir>
44 #include <QMenu>
45
46 #include <Windows.h>
47
48 ////////////////////////////////////////////////////////////
49 // Constructor
50 ////////////////////////////////////////////////////////////
51
52 ProcessingDialog::ProcessingDialog(FileListModel *fileListModel, AudioFileModel *metaInfo, SettingsModel *settings, QWidget *parent)
53 :
54         QDialog(parent),
55         m_settings(settings),
56         m_metaInfo(metaInfo)
57 {
58         //Init the dialog, from the .ui file
59         setupUi(this);
60         setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint);
61         
62         //Setup version info
63         label_versionInfo->setText(QString().sprintf("v%d.%02d %s (Build %d)", lamexp_version_major(), lamexp_version_minor(), lamexp_version_release(), lamexp_version_build()));
64         label_versionInfo->installEventFilter(this);
65
66         //Register meta type
67         qRegisterMetaType<QUuid>("QUuid");
68
69         //Center window in screen
70         QRect desktopRect = QApplication::desktop()->screenGeometry();
71         QRect thisRect = this->geometry();
72         move((desktopRect.width() - thisRect.width()) / 2, (desktopRect.height() - thisRect.height()) / 2);
73         setMinimumSize(thisRect.width(), thisRect.height());
74
75         //Enable buttons
76         connect(button_AbortProcess, SIGNAL(clicked()), this, SLOT(abortEncoding()));
77         
78         //Init progress indicator
79         m_progressIndicator = new QMovie(":/images/Working.gif");
80         label_headerWorking->setMovie(m_progressIndicator);
81         progressBar->setValue(0);
82
83         //Init progress model
84         m_progressModel = new ProgressModel();
85         view_log->setModel(m_progressModel);
86         view_log->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
87         view_log->verticalHeader()->hide();
88         view_log->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);
89         view_log->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
90         connect(m_progressModel, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(progressModelChanged()));
91         connect(m_progressModel, SIGNAL(modelReset()), this, SLOT(progressModelChanged()));
92         connect(view_log, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(logViewDoubleClicked(QModelIndex)));
93
94         //Create context menu
95         m_contextMenu = new QMenu();
96         QAction *contextMenuAction = m_contextMenu->addAction(QIcon(":/icons/zoom.png"), "Show details for selected job");
97         view_log->setContextMenuPolicy(Qt::CustomContextMenu);
98         connect(view_log, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenuTriggered(QPoint)));
99         connect(contextMenuAction, SIGNAL(triggered(bool)), this, SLOT(contextMenuActionTriggered()));
100         
101         //Enque jobs
102         if(fileListModel)
103         {
104                 for(int i = 0; i < fileListModel->rowCount(); i++)
105                 {
106                         m_pendingJobs.append(fileListModel->getFile(fileListModel->index(i,0)));
107                 }
108         }
109
110         //Init other vars
111         m_runningThreads = 0;
112         m_currentFile = 0;
113         m_succeededFiles = 0;
114         m_failedFiles = 0;
115         m_userAborted = false;
116 }
117
118 ////////////////////////////////////////////////////////////
119 // Destructor
120 ////////////////////////////////////////////////////////////
121
122 ProcessingDialog::~ProcessingDialog(void)
123 {
124         view_log->setModel(NULL);
125         if(m_progressIndicator) m_progressIndicator->stop();
126         LAMEXP_DELETE(m_progressIndicator);
127         LAMEXP_DELETE(m_progressModel);
128         LAMEXP_DELETE(m_contextMenu);
129
130         while(!m_threadList.isEmpty())
131         {
132                 ProcessThread *thread = m_threadList.takeFirst();
133                 thread->terminate();
134                 thread->wait(15000);
135                 delete thread;
136         }
137 }
138
139 ////////////////////////////////////////////////////////////
140 // EVENTS
141 ////////////////////////////////////////////////////////////
142
143 void ProcessingDialog::showEvent(QShowEvent *event)
144 {
145         setCloseButtonEnabled(false);
146         button_closeDialog->setEnabled(false);
147         button_AbortProcess->setEnabled(false);
148
149         if(!SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS))
150         {
151                 SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
152         }
153
154         QTimer::singleShot(1000, this, SLOT(initEncoding()));
155 }
156
157 void ProcessingDialog::closeEvent(QCloseEvent *event)
158 {
159         if(!button_closeDialog->isEnabled()) event->ignore();
160 }
161
162 bool ProcessingDialog::eventFilter(QObject *obj, QEvent *event)
163 {
164         static QColor defaultColor = QColor();
165
166         if(obj == label_versionInfo)
167         {
168                 if(event->type() == QEvent::Enter)
169                 {
170                         QPalette palette = label_versionInfo->palette();
171                         defaultColor = palette.color(QPalette::Normal, QPalette::WindowText);
172                         palette.setColor(QPalette::Normal, QPalette::WindowText, Qt::red);
173                         label_versionInfo->setPalette(palette);
174                 }
175                 else if(event->type() == QEvent::Leave)
176                 {
177                         QPalette palette = label_versionInfo->palette();
178                         palette.setColor(QPalette::Normal, QPalette::WindowText, defaultColor);
179                         label_versionInfo->setPalette(palette);
180                 }
181                 else if(event->type() == QEvent::MouseButtonPress)
182                 {
183                         QUrl url("http://mulder.dummwiedeutsch.de/");
184                         QDesktopServices::openUrl(url);
185                 }
186         }
187
188         return false;
189 }
190
191 ////////////////////////////////////////////////////////////
192 // SLOTS
193 ////////////////////////////////////////////////////////////
194
195 void ProcessingDialog::initEncoding(void)
196 {
197         m_runningThreads = 0;
198         m_currentFile = 0;
199         m_succeededFiles = 0;
200         m_failedFiles = 0;
201         m_userAborted = false;
202         m_playList.clear();
203         
204         label_progress->setText("Encoding files, please wait...");
205         m_progressIndicator->start();
206         
207         button_closeDialog->setEnabled(false);
208         button_AbortProcess->setEnabled(true);
209         progressBar->setRange(0, m_pendingJobs.count());
210
211         lamexp_cpu_t cpuFeatures = lamexp_detect_cpu_features();
212
213         for(int i = 0; i < min(max(cpuFeatures.count, 1), 4); i++)
214         {
215                 startNextJob();
216         }
217 }
218
219 void ProcessingDialog::abortEncoding(void)
220 {
221         m_userAborted = true;
222         button_AbortProcess->setEnabled(false);
223         
224         for(int i = 0; i < m_threadList.count(); i++)
225         {
226                 m_threadList.at(i)->abort();
227         }
228 }
229
230 void ProcessingDialog::doneEncoding(void)
231 {
232         m_runningThreads--;
233
234         progressBar->setValue(progressBar->value() + 1);
235         label_progress->setText(QString("Encoding: %1 files of %2 completed so far, please wait...").arg(QString::number(progressBar->value()), QString::number(progressBar->maximum())));
236         
237         int index = m_threadList.indexOf(dynamic_cast<ProcessThread*>(QWidget::sender()));
238         if(index >= 0)
239         {
240                 m_threadList.takeAt(index)->deleteLater();
241         }
242
243         if(!m_pendingJobs.isEmpty() && !m_userAborted)
244         {
245                 startNextJob();
246                 qDebug("Running jobs: %u", m_runningThreads);
247                 return;
248         }
249         
250         if(m_runningThreads > 0)
251         {
252                 qDebug("Running jobs: %u", m_runningThreads);
253                 return;
254         }
255
256         qDebug("Running jobs: %u", m_runningThreads);
257
258         if(!m_userAborted && m_settings->createPlaylist() && !m_settings->outputToSourceDir())
259         {
260                 label_progress->setText("Creatig the playlist file, please wait...");
261                 QApplication::processEvents();
262                 writePlayList();
263         }
264         
265         if(m_userAborted)
266         {
267                 label_progress->setText("Process was aborted by the user!");
268         }
269         else
270         {
271                 if(m_failedFiles)
272                 {
273                         label_progress->setText(QString("Error: %1 of %2 files failed. See the log for details!").arg(QString::number(m_failedFiles), QString::number(m_failedFiles + m_succeededFiles)));
274                 }
275                 else
276                 {
277                         label_progress->setText("Alle files completed successfully.");
278                 }
279         }
280         
281         setCloseButtonEnabled(true);
282         button_closeDialog->setEnabled(true);
283         button_AbortProcess->setEnabled(false);
284
285         m_progressIndicator->stop();
286         progressBar->setValue(100);
287 }
288
289 void ProcessingDialog::processFinished(const QUuid &jobId, const QString &outFileName, bool success)
290 {
291         if(success)
292         {
293                 m_succeededFiles++;
294                 m_playList.append(outFileName);
295         }
296         else
297         {
298                 m_failedFiles++;
299         }
300 }
301
302 void ProcessingDialog::progressModelChanged(void)
303 {
304         view_log->scrollToBottom();
305 }
306
307 void ProcessingDialog::logViewDoubleClicked(const QModelIndex &index)
308 {
309         if(m_runningThreads == 0)
310         {
311                 const QStringList &logFile = m_progressModel->getLogFile(index);
312                 LogViewDialog *logView = new LogViewDialog(this);
313                 logView->setWindowTitle(QString("LameXP - [%1]").arg(m_progressModel->data(index, Qt::DisplayRole).toString()));
314                 logView->exec(logFile);
315                 LAMEXP_DELETE(logView);
316         }
317         else
318         {
319                 MessageBeep(MB_ICONWARNING);
320         }
321 }
322
323 void ProcessingDialog::contextMenuTriggered(const QPoint &pos)
324 {
325         m_contextMenu->popup(view_log->mapToGlobal(pos));
326 }
327
328 void ProcessingDialog::contextMenuActionTriggered(void)
329 {
330         QModelIndex index = view_log->indexAt(view_log->mapFromGlobal(m_contextMenu->pos()));
331         logViewDoubleClicked(index.isValid() ? index : view_log->currentIndex());
332 }
333
334 ////////////////////////////////////////////////////////////
335 // Private Functions
336 ////////////////////////////////////////////////////////////
337
338 void ProcessingDialog::startNextJob(void)
339 {
340         if(m_pendingJobs.isEmpty())
341         {
342                 return;
343         }
344         
345         m_currentFile++;
346         AudioFileModel currentFile = updateMetaInfo(m_pendingJobs.takeFirst());
347         AbstractEncoder *encoder = NULL;
348         
349         switch(m_settings->compressionEncoder())
350         {
351         case SettingsModel::MP3Encoder:
352                 {
353                         MP3Encoder *mp3Encoder = new MP3Encoder();
354                         mp3Encoder->setBitrate(m_settings->compressionBitrate());
355                         mp3Encoder->setRCMode(m_settings->compressionRCMode());
356                         encoder = mp3Encoder;
357                 }
358                 break;
359         default:
360                 throw "Unsupported encoder!";
361         }
362
363         ProcessThread *thread = new ProcessThread(currentFile, (m_settings->outputToSourceDir() ? QFileInfo(currentFile.filePath()).absolutePath(): m_settings->outputDir()), encoder);
364         m_threadList.append(thread);
365         connect(thread, SIGNAL(finished()), this, SLOT(doneEncoding()), Qt::QueuedConnection);
366         connect(thread, SIGNAL(processStateInitialized(QUuid,QString,QString,int)), m_progressModel, SLOT(addJob(QUuid,QString,QString,int)), Qt::QueuedConnection);
367         connect(thread, SIGNAL(processStateChanged(QUuid,QString,int)), m_progressModel, SLOT(updateJob(QUuid,QString,int)), Qt::QueuedConnection);
368         connect(thread, SIGNAL(processStateFinished(QUuid,QString,bool)), this, SLOT(processFinished(QUuid,QString,bool)), Qt::QueuedConnection);
369         connect(thread, SIGNAL(processMessageLogged(QUuid,QString)), m_progressModel, SLOT(appendToLog(QUuid,QString)), Qt::QueuedConnection);
370         m_runningThreads++;
371         thread->start();
372 }
373
374 void ProcessingDialog::writePlayList(void)
375 {
376         QString playListName = (m_metaInfo->fileAlbum().isEmpty() ? "Playlist" : m_metaInfo->fileAlbum());
377
378         const static char *invalidChars = "\\/:*?\"<>|";
379         for(int i = 0; invalidChars[i]; i++)
380         {
381                 playListName.replace(invalidChars[i], ' ');
382                 playListName = playListName.simplified();
383         }
384         
385         QString playListFile = QString("%1/%2.m3u").arg(m_settings->outputDir(), playListName);
386
387         int counter = 1;
388         while(QFileInfo(playListFile).exists())
389         {
390                 playListFile = QString("%1/%2 (%3).m3u").arg(m_settings->outputDir(), playListName, QString::number(++counter));
391         }
392         
393         QFile playList(playListFile);
394         if(playList.open(QIODevice::WriteOnly))
395         {
396                 playList.write("#EXTM3U\r\n");
397                 for(int i = 0; i < m_playList.count(); i++)
398                 {
399                         playList.write(QFileInfo(m_playList.at(i)).fileName().toUtf8().constData());
400                         playList.write("\r\n");
401                 }
402                 playList.close();
403         }
404         else
405         {
406                 QMessageBox::warning(this, "Playlist creation failed", QString("The playlist file could not be created:<br><nobr>%1</nobr>").arg(playListFile));
407         }
408 }
409
410 AudioFileModel ProcessingDialog::updateMetaInfo(const AudioFileModel &audioFile)
411 {
412         if(!m_settings->writeMetaTags())
413         {
414                 return AudioFileModel(audioFile.filePath());
415         }
416         
417         AudioFileModel result = audioFile;
418
419         if(!m_metaInfo->fileArtist().isEmpty()) result.setFileArtist(m_metaInfo->fileArtist());
420         if(!m_metaInfo->fileAlbum().isEmpty()) result.setFileAlbum(m_metaInfo->fileAlbum());
421         if(!m_metaInfo->fileGenre().isEmpty()) result.setFileGenre(m_metaInfo->fileGenre());
422         if(m_metaInfo->fileYear()) result.setFileYear(m_metaInfo->fileYear());
423         if(m_metaInfo->filePosition()) result.setFileYear(m_metaInfo->filePosition() != UINT_MAX ? m_metaInfo->filePosition() : m_currentFile);
424         if(!m_metaInfo->fileComment().isEmpty()) result.setFileComment(m_metaInfo->fileComment());
425
426         return result;
427 }
428
429 void ProcessingDialog::setCloseButtonEnabled(bool enabled)
430 {
431         HMENU hMenu = GetSystemMenu((HWND) winId(), FALSE);
432         EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | (enabled ? MF_ENABLED : MF_GRAYED));
433 }