OSDN Git Service

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