OSDN Git Service

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