OSDN Git Service

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