OSDN Git Service

Added indicators for current CPU usage, RAM usage and free disk space to the processi...
[lamexp/LameXP.git] / src / Dialog_Processing.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2011 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 "Thread_CPUObserver.h"
31 #include "Thread_RAMObserver.h"
32 #include "Thread_DiskObserver.h"
33 #include "Dialog_LogView.h"
34 #include "Encoder_MP3.h"
35 #include "Encoder_Vorbis.h"
36 #include "Encoder_AAC.h"
37 #include "Encoder_AAC_FHG.h"
38 #include "Encoder_AC3.h"
39 #include "Encoder_FLAC.h"
40 #include "Encoder_Wave.h"
41 #include "Filter_Downmix.h"
42 #include "Filter_Normalize.h"
43 #include "Filter_Resample.h"
44 #include "Filter_ToneAdjust.h"
45 #include "WinSevenTaskbar.h"
46
47 #include <QApplication>
48 #include <QRect>
49 #include <QDesktopWidget>
50 #include <QMovie>
51 #include <QMessageBox>
52 #include <QTimer>
53 #include <QCloseEvent>
54 #include <QDesktopServices>
55 #include <QUrl>
56 #include <QUuid>
57 #include <QFileInfo>
58 #include <QDir>
59 #include <QMenu>
60 #include <QSystemTrayIcon>
61 #include <QProcess>
62 #include <QProgressDialog>
63
64 #include <MMSystem.h>
65
66 ////////////////////////////////////////////////////////////
67
68 //Maximum number of parallel instances
69 #define MAX_INSTANCES 16
70
71 //Maximum number of CPU cores for auto-detection
72 #define MAX_CPU_COUNT 4
73
74 ////////////////////////////////////////////////////////////
75
76 #define CHANGE_BACKGROUND_COLOR(WIDGET, COLOR) \
77 { \
78         QPalette palette = WIDGET->palette(); \
79         palette.setColor(QPalette::Background, COLOR); \
80         WIDGET->setPalette(palette); \
81 }
82
83 #define SET_PROGRESS_TEXT(TXT) \
84 { \
85         label_progress->setText(TXT); \
86         m_systemTray->setToolTip(QString().sprintf("LameXP v%d.%02d\n%ls", lamexp_version_major(), lamexp_version_minor(), QString(TXT).utf16())); \
87 }
88
89 #define SET_FONT_BOLD(WIDGET,BOLD) { QFont _font = WIDGET->font(); _font.setBold(BOLD); WIDGET->setFont(_font); }
90
91 ////////////////////////////////////////////////////////////
92 // Constructor
93 ////////////////////////////////////////////////////////////
94
95 ProcessingDialog::ProcessingDialog(FileListModel *fileListModel, AudioFileModel *metaInfo, SettingsModel *settings, QWidget *parent)
96 :
97         QDialog(parent),
98         m_systemTray(new QSystemTrayIcon(QIcon(":/icons/cd_go.png"), this)),
99         m_settings(settings),
100         m_metaInfo(metaInfo),
101         m_shutdownFlag(shutdownFlag_None),
102         m_diskObserver(NULL),
103         m_cpuObserver(NULL),
104         m_ramObserver(NULL)
105 {
106         //Init the dialog, from the .ui file
107         setupUi(this);
108         setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint);
109         
110         //Setup version info
111         label_versionInfo->setText(QString().sprintf("v%d.%02d %s (Build %d)", lamexp_version_major(), lamexp_version_minor(), lamexp_version_release(), lamexp_version_build()));
112         label_versionInfo->installEventFilter(this);
113
114         //Register meta type
115         qRegisterMetaType<QUuid>("QUuid");
116
117         //Center window in screen
118         QRect desktopRect = QApplication::desktop()->screenGeometry();
119         QRect thisRect = this->geometry();
120         move((desktopRect.width() - thisRect.width()) / 2, (desktopRect.height() - thisRect.height()) / 2);
121         setMinimumSize(thisRect.width(), thisRect.height());
122
123         //Enable buttons
124         connect(button_AbortProcess, SIGNAL(clicked()), this, SLOT(abortEncoding()));
125         
126         //Init progress indicator
127         m_progressIndicator = new QMovie(":/images/Working.gif");
128         label_headerWorking->setMovie(m_progressIndicator);
129         progressBar->setValue(0);
130
131         //Init progress model
132         m_progressModel = new ProgressModel();
133         view_log->setModel(m_progressModel);
134         view_log->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
135         view_log->verticalHeader()->hide();
136         view_log->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);
137         view_log->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
138         view_log->viewport()->installEventFilter(this);
139         connect(m_progressModel, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(progressModelChanged()));
140         connect(m_progressModel, SIGNAL(modelReset()), this, SLOT(progressModelChanged()));
141         connect(view_log, SIGNAL(activated(QModelIndex)), this, SLOT(logViewDoubleClicked(QModelIndex)));
142         connect(view_log->horizontalHeader(), SIGNAL(sectionResized(int,int,int)), this, SLOT(logViewSectionSizeChanged(int,int,int)));
143
144         //Create context menu
145         m_contextMenu = new QMenu();
146         QAction *contextMenuDetailsAction = m_contextMenu->addAction(QIcon(":/icons/zoom.png"), tr("Show details for selected job"));
147         QAction *contextMenuShowFileAction = m_contextMenu->addAction(QIcon(":/icons/folder_go.png"), tr("Browse Output File Location"));
148
149         view_log->setContextMenuPolicy(Qt::CustomContextMenu);
150         connect(view_log, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenuTriggered(QPoint)));
151         connect(contextMenuDetailsAction, SIGNAL(triggered(bool)), this, SLOT(contextMenuDetailsActionTriggered()));
152         connect(contextMenuShowFileAction, SIGNAL(triggered(bool)), this, SLOT(contextMenuShowFileActionTriggered()));
153         SET_FONT_BOLD(contextMenuDetailsAction, true);
154
155         //Enque jobs
156         if(fileListModel)
157         {
158                 for(int i = 0; i < fileListModel->rowCount(); i++)
159                 {
160                         m_pendingJobs.append(fileListModel->getFile(fileListModel->index(i,0)));
161                 }
162         }
163
164         //Translate
165         label_headerStatus->setText(QString("<b>%1</b><br>%2").arg(tr("Encoding Files"), tr("Your files are being encoded, please be patient...")));
166         
167         //Enable system tray icon
168         connect(m_systemTray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(systemTrayActivated(QSystemTrayIcon::ActivationReason)));
169
170         //Init other vars
171         m_runningThreads = 0;
172         m_currentFile = 0;
173         m_allJobs.clear();
174         m_succeededJobs.clear();
175         m_failedJobs.clear();
176         m_userAborted = false;
177 }
178
179 ////////////////////////////////////////////////////////////
180 // Destructor
181 ////////////////////////////////////////////////////////////
182
183 ProcessingDialog::~ProcessingDialog(void)
184 {
185         view_log->setModel(NULL);
186
187         if(m_progressIndicator)
188         {
189                 m_progressIndicator->stop();
190         }
191
192         if(m_diskObserver)
193         {
194                 m_diskObserver->stop();
195                 if(!m_diskObserver->wait(15000))
196                 {
197                         m_diskObserver->terminate();
198                         m_diskObserver->wait();
199                 }
200         }
201         if(m_cpuObserver)
202         {
203                 m_cpuObserver->stop();
204                 if(!m_cpuObserver->wait(15000))
205                 {
206                         m_cpuObserver->terminate();
207                         m_cpuObserver->wait();
208                 }
209         }
210         if(m_ramObserver)
211         {
212                 m_ramObserver->stop();
213                 if(!m_ramObserver->wait(15000))
214                 {
215                         m_ramObserver->terminate();
216                         m_ramObserver->wait();
217                 }
218         }
219
220         LAMEXP_DELETE(m_progressIndicator);
221         LAMEXP_DELETE(m_progressModel);
222         LAMEXP_DELETE(m_contextMenu);
223         LAMEXP_DELETE(m_systemTray);
224         LAMEXP_DELETE(m_diskObserver);
225         LAMEXP_DELETE(m_cpuObserver);
226         LAMEXP_DELETE(m_ramObserver);
227
228         WinSevenTaskbar::setOverlayIcon(this, NULL);
229         WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNoState);
230
231         while(!m_threadList.isEmpty())
232         {
233                 ProcessThread *thread = m_threadList.takeFirst();
234                 thread->terminate();
235                 thread->wait(15000);
236                 delete thread;
237         }
238 }
239
240 ////////////////////////////////////////////////////////////
241 // EVENTS
242 ////////////////////////////////////////////////////////////
243
244 void ProcessingDialog::showEvent(QShowEvent *event)
245 {
246         setCloseButtonEnabled(false);
247         button_closeDialog->setEnabled(false);
248         button_AbortProcess->setEnabled(false);
249         m_systemTray->setVisible(true);
250         
251         if(!SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS))
252         {
253                 SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
254         }
255
256         ramUsageHasChanged(0.0);
257         cpuUsageHasChanged(0.0);
258         diskUsageHasChanged(0ui64);
259
260         QTimer::singleShot(1000, this, SLOT(initEncoding()));
261 }
262
263 void ProcessingDialog::closeEvent(QCloseEvent *event)
264 {
265         if(!button_closeDialog->isEnabled())
266         {
267                 event->ignore();
268         }
269         else
270         {
271                 m_systemTray->setVisible(false);
272         }
273 }
274
275 bool ProcessingDialog::eventFilter(QObject *obj, QEvent *event)
276 {
277         static QColor defaultColor = QColor();
278
279         if(obj == label_versionInfo)
280         {
281                 if(event->type() == QEvent::Enter)
282                 {
283                         QPalette palette = label_versionInfo->palette();
284                         defaultColor = palette.color(QPalette::Normal, QPalette::WindowText);
285                         palette.setColor(QPalette::Normal, QPalette::WindowText, Qt::red);
286                         label_versionInfo->setPalette(palette);
287                 }
288                 else if(event->type() == QEvent::Leave)
289                 {
290                         QPalette palette = label_versionInfo->palette();
291                         palette.setColor(QPalette::Normal, QPalette::WindowText, defaultColor);
292                         label_versionInfo->setPalette(palette);
293                 }
294                 else if(event->type() == QEvent::MouseButtonPress)
295                 {
296                         QUrl url(lamexp_website_url());
297                         QDesktopServices::openUrl(url);
298                 }
299         }
300
301         return false;
302 }
303
304 ////////////////////////////////////////////////////////////
305 // SLOTS
306 ////////////////////////////////////////////////////////////
307
308 void ProcessingDialog::initEncoding(void)
309 {
310         m_runningThreads = 0;
311         m_currentFile = 0;
312         m_allJobs.clear();
313         m_succeededJobs.clear();
314         m_failedJobs.clear();
315         m_userAborted = false;
316         m_playList.clear();
317         
318         CHANGE_BACKGROUND_COLOR(frame_header, QColor(Qt::white));
319         SET_PROGRESS_TEXT(tr("Encoding files, please wait..."));
320         m_progressIndicator->start();
321         
322         button_closeDialog->setEnabled(false);
323         button_AbortProcess->setEnabled(true);
324         progressBar->setRange(0, m_pendingJobs.count());
325         checkBox_shutdownComputer->setEnabled(true);
326         checkBox_shutdownComputer->setChecked(false);
327
328         WinSevenTaskbar::initTaskbar();
329         WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
330         WinSevenTaskbar::setTaskbarProgress(this, 0, m_pendingJobs.count());
331         WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/control_play_blue.png"));
332
333         if(!m_diskObserver)
334         {
335                 m_diskObserver = new DiskObserverThread(m_settings->customTempPathEnabled() ? m_settings->customTempPath() : lamexp_temp_folder2());
336                 connect(m_diskObserver, SIGNAL(messageLogged(QString,bool)), m_progressModel, SLOT(addSystemMessage(QString,bool)), Qt::QueuedConnection);
337                 connect(m_diskObserver, SIGNAL(freeSpaceChanged(quint64)), this, SLOT(diskUsageHasChanged(quint64)), Qt::QueuedConnection);
338                 m_diskObserver->start();
339         }
340         if(!m_cpuObserver)
341         {
342                 m_cpuObserver = new CPUObserverThread();
343                 connect(m_cpuObserver, SIGNAL(currentUsageChanged(double)), this, SLOT(cpuUsageHasChanged(double)), Qt::QueuedConnection);
344                 m_cpuObserver->start();
345         }
346         if(!m_ramObserver)
347         {
348                 m_ramObserver = new RAMObserverThread();
349                 connect(m_ramObserver, SIGNAL(currentUsageChanged(double)), this, SLOT(ramUsageHasChanged(double)), Qt::QueuedConnection);
350                 m_ramObserver->start();
351         }
352         
353         int maximumInstances = max(min(m_settings->maximumInstances(), MAX_INSTANCES), 0);
354         if(maximumInstances < 1)
355         {
356                 lamexp_cpu_t cpuFeatures = lamexp_detect_cpu_features();
357                 maximumInstances = max(min(cpuFeatures.count, MAX_CPU_COUNT), 1);
358         }
359
360         int parallelThreadCount = max(min(maximumInstances, m_pendingJobs.count()), 1);
361         if(parallelThreadCount > 1)
362         {
363                 m_progressModel->addSystemMessage(tr("Multi-threading enabled: Running %1 instances in parallel!").arg(QString::number(parallelThreadCount)));
364         }
365
366         for(int i = 0; i < parallelThreadCount; i++)
367         {
368                 startNextJob();
369         }
370 }
371
372 void ProcessingDialog::abortEncoding(void)
373 {
374         m_userAborted = true;
375         button_AbortProcess->setEnabled(false);
376         
377         SET_PROGRESS_TEXT(tr("Aborted! Waiting for running jobs to terminate..."));
378
379         for(int i = 0; i < m_threadList.count(); i++)
380         {
381                 m_threadList.at(i)->abort();
382         }
383 }
384
385 void ProcessingDialog::doneEncoding(void)
386 {
387         m_runningThreads--;
388         progressBar->setValue(progressBar->value() + 1);
389         
390         if(!m_userAborted)
391         {
392                 SET_PROGRESS_TEXT(tr("Encoding: %1 files of %2 completed so far, please wait...").arg(QString::number(progressBar->value()), QString::number(progressBar->maximum())));
393                 WinSevenTaskbar::setTaskbarProgress(this, progressBar->value(), progressBar->maximum());
394         }
395         
396         int index = m_threadList.indexOf(dynamic_cast<ProcessThread*>(QWidget::sender()));
397         if(index >= 0)
398         {
399                 m_threadList.takeAt(index)->deleteLater();
400         }
401
402         if(!m_pendingJobs.isEmpty() && !m_userAborted)
403         {
404                 startNextJob();
405                 qDebug("Running jobs: %u", m_runningThreads);
406                 return;
407         }
408         
409         if(m_runningThreads > 0)
410         {
411                 qDebug("Running jobs: %u", m_runningThreads);
412                 return;
413         }
414
415         QApplication::setOverrideCursor(Qt::WaitCursor);
416         qDebug("Running jobs: %u", m_runningThreads);
417
418         if(!m_userAborted && m_settings->createPlaylist() && !m_settings->outputToSourceDir())
419         {
420                 SET_PROGRESS_TEXT(tr("Creating the playlist file, please wait..."));
421                 QApplication::processEvents();
422                 writePlayList();
423         }
424         
425         if(m_userAborted)
426         {
427                 CHANGE_BACKGROUND_COLOR(frame_header, QColor("#FFF3BA"));
428                 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
429                 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/error.png"));
430                 SET_PROGRESS_TEXT((m_succeededJobs.count() > 0) ? tr("Process was aborted by the user after %1 file(s)!").arg(QString::number(m_succeededJobs.count())) : tr("Process was aborted prematurely by the user!"));
431                 m_systemTray->showMessage(tr("LameXP - Aborted"), tr("Process was aborted by the user."), QSystemTrayIcon::Warning);
432                 m_systemTray->setIcon(QIcon(":/icons/cd_delete.png"));
433                 QApplication::processEvents();
434                 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ABORTED), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
435         }
436         else
437         {
438                 if(m_failedJobs.count() > 0)
439                 {
440                         CHANGE_BACKGROUND_COLOR(frame_header, QColor("#FFBABA"));
441                         WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
442                         WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/exclamation.png"));
443                         SET_PROGRESS_TEXT(tr("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())));
444                         m_systemTray->showMessage(tr("LameXP - Error"), tr("At least one file has failed!"), QSystemTrayIcon::Critical);
445                         m_systemTray->setIcon(QIcon(":/icons/cd_delete.png"));
446                         QApplication::processEvents();
447                         if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
448                 }
449                 else
450                 {
451                         CHANGE_BACKGROUND_COLOR(frame_header, QColor("#E0FFE2"));
452                         WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
453                         WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/accept.png"));
454                         SET_PROGRESS_TEXT(tr("All files completed successfully."));
455                         m_systemTray->showMessage(tr("LameXP - Done"), tr("All files completed successfully."), QSystemTrayIcon::Information);
456                         m_systemTray->setIcon(QIcon(":/icons/cd_add.png"));
457                         QApplication::processEvents();
458                         if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_SUCCESS), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
459                 }
460         }
461         
462         setCloseButtonEnabled(true);
463         button_closeDialog->setEnabled(true);
464         button_AbortProcess->setEnabled(false);
465         checkBox_shutdownComputer->setEnabled(false);
466
467         m_progressModel->restoreHiddenItems();
468         view_log->scrollToBottom();
469         m_progressIndicator->stop();
470         progressBar->setValue(progressBar->maximum());
471         WinSevenTaskbar::setTaskbarProgress(this, progressBar->value(), progressBar->maximum());
472
473         QApplication::restoreOverrideCursor();
474
475         if(!m_userAborted && checkBox_shutdownComputer->isChecked())
476         {
477                 if(shutdownComputer())
478                 {
479                         m_shutdownFlag = m_settings->hibernateComputer() ? shutdownFlag_Hibernate : shutdownFlag_TurnPowerOff;
480                         accept();
481                 }
482         }
483 }
484
485 void ProcessingDialog::processFinished(const QUuid &jobId, const QString &outFileName, bool success)
486 {
487         if(success)
488         {
489                 m_playList.insert(jobId, outFileName);
490                 m_succeededJobs.append(jobId);
491         }
492         else
493         {
494                 m_failedJobs.append(jobId);
495         }
496 }
497
498 void ProcessingDialog::progressModelChanged(void)
499 {
500         view_log->scrollToBottom();
501 }
502
503 void ProcessingDialog::logViewDoubleClicked(const QModelIndex &index)
504 {
505         if(m_runningThreads == 0)
506         {
507                 const QStringList &logFile = m_progressModel->getLogFile(index);
508                 
509                 if(!logFile.isEmpty())
510                 {
511                         LogViewDialog *logView = new LogViewDialog(this);
512                         logView->setWindowTitle(QString("LameXP - [%1]").arg(m_progressModel->data(index, Qt::DisplayRole).toString()));
513                         logView->exec(logFile);
514                         LAMEXP_DELETE(logView);
515                 }
516                 else
517                 {
518                         MessageBeep(MB_ICONWARNING);
519                 }
520         }
521         else
522         {
523                 MessageBeep(MB_ICONWARNING);
524         }
525 }
526
527 void ProcessingDialog::logViewSectionSizeChanged(int logicalIndex, int oldSize, int newSize)
528 {
529         if(logicalIndex == 1)
530         {
531                 if(QHeaderView *hdr = view_log->horizontalHeader())
532                 {
533                         hdr->setMinimumSectionSize(max(hdr->minimumSectionSize(), hdr->sectionSize(1)));
534                 }
535         }
536 }
537
538 void ProcessingDialog::contextMenuTriggered(const QPoint &pos)
539 {
540         QAbstractScrollArea *scrollArea = dynamic_cast<QAbstractScrollArea*>(QObject::sender());
541         QWidget *sender = scrollArea ? scrollArea->viewport() : dynamic_cast<QWidget*>(QObject::sender());      
542
543         if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0)
544         {
545                 m_contextMenu->popup(sender->mapToGlobal(pos));
546         }
547 }
548
549 void ProcessingDialog::contextMenuDetailsActionTriggered(void)
550 {
551         QModelIndex index = view_log->indexAt(view_log->mapFromGlobal(m_contextMenu->pos()));
552         logViewDoubleClicked(index.isValid() ? index : view_log->currentIndex());
553 }
554
555 void ProcessingDialog::contextMenuShowFileActionTriggered(void)
556 {
557         QModelIndex index = view_log->indexAt(view_log->mapFromGlobal(m_contextMenu->pos()));
558         const QUuid &jobId = m_progressModel->getJobId(index.isValid() ? index : view_log->currentIndex());
559         QString filePath = m_playList.value(jobId, QString());
560
561         if(filePath.isEmpty())
562         {
563                 MessageBeep(MB_ICONWARNING);
564                 return;
565         }
566
567         if(QFileInfo(filePath).exists())
568         {
569                 QString systemRootPath;
570
571                 QDir systemRoot(lamexp_known_folder(lamexp_folder_systemfolder));
572                 if(systemRoot.exists() && systemRoot.cdUp())
573                 {
574                         systemRootPath = systemRoot.canonicalPath();
575                 }
576
577                 if(!systemRootPath.isEmpty())
578                 {
579                         QFileInfo explorer(QString("%1/explorer.exe").arg(systemRootPath));
580                         if(explorer.exists() && explorer.isFile())
581                         {
582                                 QProcess::execute(explorer.canonicalFilePath(), QStringList() << "/select," << QDir::toNativeSeparators(QFileInfo(filePath).canonicalFilePath()));
583                                 return;
584                         }
585                 }
586                 else
587                 {
588                         qWarning("SystemRoot directory could not be detected!");
589                 }
590         }
591         else
592         {
593                 qWarning("File not found: %s", filePath.toLatin1().constData());
594                 MessageBeep(MB_ICONERROR);
595         }
596 }
597
598 ////////////////////////////////////////////////////////////
599 // Private Functions
600 ////////////////////////////////////////////////////////////
601
602 void ProcessingDialog::startNextJob(void)
603 {
604         if(m_pendingJobs.isEmpty())
605         {
606                 return;
607         }
608         
609         m_currentFile++;
610         AudioFileModel currentFile = updateMetaInfo(m_pendingJobs.takeFirst());
611         AbstractEncoder *encoder = NULL;
612         bool nativeResampling = false;
613
614         //Create encoder instance
615         switch(m_settings->compressionEncoder())
616         {
617         case SettingsModel::MP3Encoder:
618                 {
619                         MP3Encoder *mp3Encoder = new MP3Encoder();
620                         mp3Encoder->setBitrate(m_settings->compressionBitrate());
621                         mp3Encoder->setRCMode(m_settings->compressionRCMode());
622                         mp3Encoder->setAlgoQuality(m_settings->lameAlgoQuality());
623                         if(m_settings->bitrateManagementEnabled())
624                         {
625                                 mp3Encoder->setBitrateLimits(m_settings->bitrateManagementMinRate(), m_settings->bitrateManagementMaxRate());
626                         }
627                         if(m_settings->samplingRate() > 0)
628                         {
629                                 mp3Encoder->setSamplingRate(SettingsModel::samplingRates[m_settings->samplingRate()]);
630                                 nativeResampling = true;
631                         }
632                         mp3Encoder->setChannelMode(m_settings->lameChannelMode());
633                         mp3Encoder->setCustomParams(m_settings->customParametersLAME());
634                         encoder = mp3Encoder;
635                 }
636                 break;
637         case SettingsModel::VorbisEncoder:
638                 {
639                         VorbisEncoder *vorbisEncoder = new VorbisEncoder();
640                         vorbisEncoder->setBitrate(m_settings->compressionBitrate());
641                         vorbisEncoder->setRCMode(m_settings->compressionRCMode());
642                         if(m_settings->bitrateManagementEnabled())
643                         {
644                                 vorbisEncoder->setBitrateLimits(m_settings->bitrateManagementMinRate(), m_settings->bitrateManagementMaxRate());
645                         }
646                         if(m_settings->samplingRate() > 0)
647                         {
648                                 vorbisEncoder->setSamplingRate(SettingsModel::samplingRates[m_settings->samplingRate()]);
649                                 nativeResampling = true;
650                         }
651                         vorbisEncoder->setCustomParams(m_settings->customParametersOggEnc());
652                         encoder = vorbisEncoder;
653                 }
654                 break;
655         case SettingsModel::AACEncoder:
656                 {
657                         if(lamexp_check_tool("fhgaacenc.exe") && lamexp_check_tool("enc_fhgaac.dll"))
658                         {
659                                 FHGAACEncoder *aacEncoder = new FHGAACEncoder();
660                                 aacEncoder->setBitrate(m_settings->compressionBitrate());
661                                 aacEncoder->setRCMode(m_settings->compressionRCMode());
662                                 aacEncoder->setProfile(m_settings->aacEncProfile());
663                                 aacEncoder->setCustomParams(m_settings->customParametersAacEnc());
664                                 encoder = aacEncoder;
665                         }
666                         else
667                         {
668                                 AACEncoder *aacEncoder = new AACEncoder();
669                                 aacEncoder->setBitrate(m_settings->compressionBitrate());
670                                 aacEncoder->setRCMode(m_settings->compressionRCMode());
671                                 aacEncoder->setEnable2Pass(m_settings->neroAACEnable2Pass());
672                                 aacEncoder->setProfile(m_settings->aacEncProfile());
673                                 aacEncoder->setCustomParams(m_settings->customParametersAacEnc());
674                                 encoder = aacEncoder;
675                         }
676                 }
677                 break;
678         case SettingsModel::AC3Encoder:
679                 {
680                         AC3Encoder *ac3Encoder = new AC3Encoder();
681                         ac3Encoder->setBitrate(m_settings->compressionBitrate());
682                         ac3Encoder->setRCMode(m_settings->compressionRCMode());
683                         ac3Encoder->setCustomParams(m_settings->customParametersAften());
684                         ac3Encoder->setAudioCodingMode(m_settings->aftenAudioCodingMode());
685                         ac3Encoder->setDynamicRangeCompression(m_settings->aftenDynamicRangeCompression());
686                         ac3Encoder->setExponentSearchSize(m_settings->aftenExponentSearchSize());
687                         ac3Encoder->setFastBitAllocation(m_settings->aftenFastBitAllocation());
688                         encoder = ac3Encoder;
689                 }
690                 break;
691         case SettingsModel::FLACEncoder:
692                 {
693                         FLACEncoder *flacEncoder = new FLACEncoder();
694                         flacEncoder->setBitrate(m_settings->compressionBitrate());
695                         flacEncoder->setRCMode(m_settings->compressionRCMode());
696                         flacEncoder->setCustomParams(m_settings->customParametersFLAC());
697                         encoder = flacEncoder;
698                 }
699                 break;
700         case SettingsModel::PCMEncoder:
701                 {
702                         WaveEncoder *waveEncoder = new WaveEncoder();
703                         waveEncoder->setBitrate(m_settings->compressionBitrate());
704                         waveEncoder->setRCMode(m_settings->compressionRCMode());
705                         encoder = waveEncoder;
706                 }
707                 break;
708         default:
709                 throw "Unsupported encoder!";
710         }
711
712         //Create processing thread
713         ProcessThread *thread = new ProcessThread
714         (
715                 currentFile,
716                 (m_settings->outputToSourceDir() ? QFileInfo(currentFile.filePath()).absolutePath() : m_settings->outputDir()),
717                 (m_settings->customTempPathEnabled() ? m_settings->customTempPath() : lamexp_temp_folder2()),
718                 encoder,
719                 m_settings->prependRelativeSourcePath() && (!m_settings->outputToSourceDir())
720         );
721
722         //Add audio filters
723         if(m_settings->forceStereoDownmix())
724         {
725                 thread->addFilter(new DownmixFilter());
726         }
727         if((m_settings->samplingRate() > 0) && !nativeResampling)
728         {
729                 if(SettingsModel::samplingRates[m_settings->samplingRate()] != currentFile.formatAudioSamplerate() || currentFile.formatAudioSamplerate() == 0)
730                 {
731                         thread->addFilter(new ResampleFilter(SettingsModel::samplingRates[m_settings->samplingRate()]));
732                 }
733         }
734         if((m_settings->toneAdjustBass() != 0) || (m_settings->toneAdjustTreble() != 0))
735         {
736                 thread->addFilter(new ToneAdjustFilter(m_settings->toneAdjustBass(), m_settings->toneAdjustTreble()));
737         }
738         if(m_settings->normalizationFilterEnabled())
739         {
740                 thread->addFilter(new NormalizeFilter(m_settings->normalizationFilterMaxVolume(), m_settings->normalizationFilterEqualizationMode()));
741         }
742         if(m_settings->renameOutputFilesEnabled() && (!m_settings->renameOutputFilesPattern().simplified().isEmpty()))
743         {
744                 thread->setRenamePattern(m_settings->renameOutputFilesPattern());
745         }
746
747         m_threadList.append(thread);
748         m_allJobs.append(thread->getId());
749         
750         //Connect thread signals
751         connect(thread, SIGNAL(finished()), this, SLOT(doneEncoding()), Qt::QueuedConnection);
752         connect(thread, SIGNAL(processStateInitialized(QUuid,QString,QString,int)), m_progressModel, SLOT(addJob(QUuid,QString,QString,int)), Qt::QueuedConnection);
753         connect(thread, SIGNAL(processStateChanged(QUuid,QString,int)), m_progressModel, SLOT(updateJob(QUuid,QString,int)), Qt::QueuedConnection);
754         connect(thread, SIGNAL(processStateFinished(QUuid,QString,bool)), this, SLOT(processFinished(QUuid,QString,bool)), Qt::QueuedConnection);
755         connect(thread, SIGNAL(processMessageLogged(QUuid,QString)), m_progressModel, SLOT(appendToLog(QUuid,QString)), Qt::QueuedConnection);
756         
757         //Give it a go!
758         m_runningThreads++;
759         thread->start();
760 }
761
762 void ProcessingDialog::writePlayList(void)
763 {
764         if(m_succeededJobs.count() <= 0 || m_allJobs.count() <= 0)
765         {
766                 qWarning("WritePlayList: Nothing to do!");
767                 return;
768         }
769         
770         //Init local variables
771         QStringList list;
772         QRegExp regExp1("\\[\\d\\d\\][^/\\\\]+$", Qt::CaseInsensitive);
773         QRegExp regExp2("\\(\\d\\d\\)[^/\\\\]+$", Qt::CaseInsensitive);
774         QRegExp regExp3("\\d\\d[^/\\\\]+$", Qt::CaseInsensitive);
775         bool usePrefix[3] = {true, true, true};
776         bool useUtf8 = false;
777         int counter = 1;
778
779         //Generate playlist name
780         QString playListName = (m_metaInfo->fileAlbum().isEmpty() ? "Playlist" : m_metaInfo->fileAlbum());
781         if(!m_metaInfo->fileArtist().isEmpty())
782         {
783                 playListName = QString("%1 - %2").arg(m_metaInfo->fileArtist(), playListName);
784         }
785
786         //Clean playlist name
787         playListName = lamexp_clean_filename(playListName);
788
789         //Create list of audio files
790         for(int i = 0; i < m_allJobs.count(); i++)
791         {
792                 if(!m_succeededJobs.contains(m_allJobs.at(i))) continue;
793                 list << QDir::toNativeSeparators(QDir(m_settings->outputDir()).relativeFilePath(m_playList.value(m_allJobs.at(i), "N/A")));
794         }
795
796         //Use prefix?
797         for(int i = 0; i < list.count(); i++)
798         {
799                 if(regExp1.indexIn(list.at(i)) < 0) usePrefix[0] = false;
800                 if(regExp2.indexIn(list.at(i)) < 0) usePrefix[1] = false;
801                 if(regExp3.indexIn(list.at(i)) < 0) usePrefix[2] = false;
802         }
803         if(usePrefix[0] || usePrefix[1] || usePrefix[2])
804         {
805                 playListName.prepend(usePrefix[0] ? "[00] " : (usePrefix[1] ? "(00) " : "00 "));
806         }
807
808         //Do we need an UTF-8 playlist?
809         for(int i = 0; i < list.count(); i++)
810         {
811                 if(wcscmp(QWCHAR(QString::fromLatin1(list.at(i).toLatin1().constData())), QWCHAR(list.at(i))))
812                 {
813                         useUtf8 = true;
814                         break;
815                 }
816         }
817
818         //Generate playlist output file
819         QString playListFile = QString("%1/%2.%3").arg(m_settings->outputDir(), playListName, (useUtf8 ? "m3u8" : "m3u"));
820         while(QFileInfo(playListFile).exists())
821         {
822                 playListFile = QString("%1/%2 (%3).%4").arg(m_settings->outputDir(), playListName, QString::number(++counter), (useUtf8 ? "m3u8" : "m3u"));
823         }
824
825         //Now write playlist to output file
826         QFile playList(playListFile);
827         if(playList.open(QIODevice::WriteOnly))
828         {
829                 if(useUtf8)
830                 {
831                         playList.write("\xef\xbb\xbf");
832                 }
833                 playList.write("#EXTM3U\r\n");
834                 while(!list.isEmpty())
835                 {
836                         playList.write(useUtf8 ? list.takeFirst().toUtf8().constData() : list.takeFirst().toLatin1().constData());
837                         playList.write("\r\n");
838                 }
839                 playList.close();
840         }
841         else
842         {
843                 QMessageBox::warning(this, tr("Playlist creation failed"), QString("%1<br><nobr>%2</nobr>").arg(tr("The playlist file could not be created:"), playListFile));
844         }
845 }
846
847 AudioFileModel ProcessingDialog::updateMetaInfo(const AudioFileModel &audioFile)
848 {
849         if(!m_settings->writeMetaTags())
850         {
851                 return AudioFileModel(audioFile, false);
852         }
853         
854         AudioFileModel result = audioFile;
855         result.updateMetaInfo(*m_metaInfo);
856         
857         if(m_metaInfo->filePosition() == UINT_MAX)
858         {
859                 result.setFilePosition(m_currentFile);
860         }
861
862         return result;
863 }
864
865 void ProcessingDialog::setCloseButtonEnabled(bool enabled)
866 {
867         HMENU hMenu = GetSystemMenu((HWND) winId(), FALSE);
868         EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | (enabled ? MF_ENABLED : MF_GRAYED));
869 }
870
871 void ProcessingDialog::systemTrayActivated(QSystemTrayIcon::ActivationReason reason)
872 {
873         if(reason == QSystemTrayIcon::DoubleClick)
874         {
875                 SetForegroundWindow(this->winId());
876         }
877 }
878
879 void ProcessingDialog::cpuUsageHasChanged(const double val)
880 {
881         
882         this->label_cpu->setText(QString().sprintf(" %d%%", qRound(val * 100.0)));
883 }
884
885 void ProcessingDialog::ramUsageHasChanged(const double val)
886 {
887         
888         this->label_ram->setText(QString().sprintf(" %d%%", qRound(val * 100.0)));
889 }
890
891 void ProcessingDialog::diskUsageHasChanged(const quint64 val)
892 {
893         int postfix = 0;
894         const char *postfixStr[6] = {"B", "KB", "MB", "GB", "TB", "PB"};
895         double space = static_cast<double>(val);
896
897         while((space >= 1000.0) && (postfix < 5))
898         {
899                 space = space / 1024.0;
900                 postfix++;
901         }
902
903         this->label_disk->setText(QString().sprintf(" %3.1f %s", space, postfixStr[postfix]));
904 }
905
906 bool ProcessingDialog::shutdownComputer(void)
907 {
908         const int iTimeout = m_settings->hibernateComputer() ? 10 : 30;
909         const Qt::WindowFlags flags = Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowSystemMenuHint;
910         const QString text = QString("%1%2%1").arg(QString().fill(' ', 18), tr("Warning: Computer will shutdown in %1 seconds..."));
911         
912         qWarning("Initiating shutdown sequence!");
913         
914         QProgressDialog progressDialog(text.arg(iTimeout), tr("Cancel Shutdown"), 0, iTimeout + 1, this, flags);
915         QPushButton *cancelButton = new QPushButton(tr("Cancel Shutdown"), &progressDialog);
916         cancelButton->setIcon(QIcon(":/icons/power_on.png"));
917         progressDialog.setModal(true);
918         progressDialog.setAutoClose(false);
919         progressDialog.setAutoReset(false);
920         progressDialog.setWindowIcon(QIcon(":/icons/power_off.png"));
921         progressDialog.setCancelButton(cancelButton);
922         progressDialog.show();
923         
924         QApplication::processEvents();
925
926         if(m_settings->soundsEnabled())
927         {
928                 QApplication::setOverrideCursor(Qt::WaitCursor);
929                 PlaySound(MAKEINTRESOURCE(IDR_WAVE_SHUTDOWN), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
930                 QApplication::restoreOverrideCursor();
931         }
932
933         QTimer timer;
934         timer.setInterval(1000);
935         timer.start();
936
937         QEventLoop eventLoop(this);
938         connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
939         connect(&progressDialog, SIGNAL(canceled()), &eventLoop, SLOT(quit()));
940
941         for(int i = 1; i <= iTimeout; i++)
942         {
943                 eventLoop.exec();
944                 if(progressDialog.wasCanceled())
945                 {
946                         progressDialog.close();
947                         return false;
948                 }
949                 progressDialog.setValue(i+1);
950                 progressDialog.setLabelText(text.arg(iTimeout-i));
951                 if(iTimeout-i == 3) progressDialog.setCancelButton(NULL);
952                 QApplication::processEvents();
953                 PlaySound(MAKEINTRESOURCE((i < iTimeout) ? IDR_WAVE_BEEP : IDR_WAVE_BEEP_LONG), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
954         }
955         
956         progressDialog.close();
957         return true;
958 }