OSDN Git Service

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