OSDN Git Service

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