OSDN Git Service

Moved JobObject as well as the remaining GUI functions into the MUtilities library.
[lamexp/LameXP.git] / src / Dialog_Processing.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2014 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, but always including the *additional*
9 // restrictions defined in the "License.txt" file.
10 //
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 // GNU General Public License for more details.
15 //
16 // You should have received a copy of the GNU General Public License along
17 // with this program; if not, write to the Free Software Foundation, Inc.,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 //
20 // http://www.gnu.org/licenses/gpl-2.0.txt
21 ///////////////////////////////////////////////////////////////////////////////
22
23 #include "Dialog_Processing.h"
24
25 //UIC includes
26 #include "UIC_ProcessingDialog.h"
27
28 //Internal
29 #include "Global.h"
30 #include "Model_FileList.h"
31 #include "Model_Progress.h"
32 #include "Model_Settings.h"
33 #include "Thread_Process.h"
34 #include "Thread_CPUObserver.h"
35 #include "Thread_RAMObserver.h"
36 #include "Thread_DiskObserver.h"
37 #include "Dialog_LogView.h"
38 #include "Registry_Decoder.h"
39 #include "Registry_Encoder.h"
40 #include "Filter_Downmix.h"
41 #include "Filter_Normalize.h"
42 #include "Filter_Resample.h"
43 #include "Filter_ToneAdjust.h"
44 #include "WinSevenTaskbar.h"
45
46 //MUtils
47 #include <MUtils/Global.h>
48 #include <MUtils/OSSupport.h>
49 #include <MUtils/GUI.h>
50 #include <MUtils/CPUFeatures.h>
51 #include <MUtils/Sound.h>
52
53 //Qt
54 #include <QApplication>
55 #include <QRect>
56 #include <QDesktopWidget>
57 #include <QMovie>
58 #include <QMessageBox>
59 #include <QTimer>
60 #include <QCloseEvent>
61 #include <QDesktopServices>
62 #include <QUrl>
63 #include <QUuid>
64 #include <QFileInfo>
65 #include <QDir>
66 #include <QMenu>
67 #include <QSystemTrayIcon>
68 #include <QProcess>
69 #include <QProgressDialog>
70 #include <QResizeEvent>
71 #include <QTime>
72 #include <QElapsedTimer>
73 #include <QThreadPool>
74
75 #include <math.h>
76 #include <float.h>
77 #include <stdint.h>
78
79 ////////////////////////////////////////////////////////////
80
81 //Maximum number of parallel instances
82 #define MAX_INSTANCES 32U
83
84 //Function to calculate the number of instances
85 static int cores2instances(int cores);
86
87 ////////////////////////////////////////////////////////////
88
89 #define CHANGE_BACKGROUND_COLOR(WIDGET, COLOR) do \
90 { \
91         QPalette palette = WIDGET->palette(); \
92         palette.setColor(QPalette::Background, COLOR); \
93         WIDGET->setPalette(palette); \
94 } \
95 while(0)
96
97 #define SET_PROGRESS_TEXT(TXT) do \
98 { \
99         ui->label_progress->setText(TXT); \
100         m_systemTray->setToolTip(QString().sprintf("LameXP v%d.%02d\n%ls", lamexp_version_major(), lamexp_version_minor(), QString(TXT).utf16())); \
101 } \
102 while(0)
103
104 #define SET_FONT_BOLD(WIDGET,BOLD) do \
105 { \
106         QFont _font = WIDGET->font(); \
107         _font.setBold(BOLD); WIDGET->setFont(_font); \
108 } \
109 while(0)
110
111 #define SET_TEXT_COLOR(WIDGET, COLOR) do \
112 { \
113         QPalette _palette = WIDGET->palette(); \
114         _palette.setColor(QPalette::WindowText, (COLOR)); \
115         _palette.setColor(QPalette::Text, (COLOR)); \
116         WIDGET->setPalette(_palette); \
117 } \
118 while(0)
119
120 #define UPDATE_MIN_WIDTH(WIDGET) do \
121 { \
122         if(WIDGET->width() > WIDGET->minimumWidth()) WIDGET->setMinimumWidth(WIDGET->width()); \
123 } \
124 while(0)
125
126 #define PLAY_SOUND_OPTIONAL(NAME, ASYNC) do \
127 { \
128         if(m_settings->soundsEnabled()) MUtils::Sound::play_sound((NAME), (ASYNC)); \
129 } \
130 while(0)
131
132 #define IS_VBR(RC_MODE) ((RC_MODE) == SettingsModel::VBRMode)
133
134 ////////////////////////////////////////////////////////////
135
136 //Dummy class for UserData
137 class IntUserData : public QObjectUserData
138 {
139 public:
140         IntUserData(int value) : m_value(value) {/*NOP*/}
141         int value(void) { return m_value; }
142         void setValue(int value) { m_value = value; }
143 private:
144         int m_value;
145 };
146
147 ////////////////////////////////////////////////////////////
148 // Constructor
149 ////////////////////////////////////////////////////////////
150
151 ProcessingDialog::ProcessingDialog(FileListModel *fileListModel, const AudioFileModel_MetaInfo *metaInfo, SettingsModel *settings, QWidget *parent)
152 :
153         QDialog(parent),
154         ui(new Ui::ProcessingDialog),
155         m_systemTray(new QSystemTrayIcon(QIcon(":/icons/cd_go.png"), this)),
156         m_settings(settings),
157         m_metaInfo(metaInfo),
158         m_shutdownFlag(shutdownFlag_None),
159         m_threadPool(NULL),
160         m_diskObserver(NULL),
161         m_cpuObserver(NULL),
162         m_ramObserver(NULL),
163         m_progressViewFilter(-1),
164         m_initThreads(0),
165         m_defaultColor(new QColor()),
166         m_firstShow(true)
167 {
168         //Init the dialog, from the .ui file
169         ui->setupUi(this);
170         setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint);
171         
172         //Update the window icon
173         MUtils::GUI::set_window_icon(this, lamexp_app_icon(), true);
174
175         //Update header icon
176         ui->label_headerIcon->setPixmap(lamexp_app_icon().pixmap(ui->label_headerIcon->size()));
177         
178         //Setup version info
179         ui->label_versionInfo->setText(QString().sprintf("v%d.%02d %s (Build %d)", lamexp_version_major(), lamexp_version_minor(), lamexp_version_release(), lamexp_version_build()));
180         ui->label_versionInfo->installEventFilter(this);
181
182         //Register meta type
183         qRegisterMetaType<QUuid>("QUuid");
184
185         //Center window in screen
186         QRect desktopRect = QApplication::desktop()->screenGeometry();
187         QRect thisRect = this->geometry();
188         move((desktopRect.width() - thisRect.width()) / 2, (desktopRect.height() - thisRect.height()) / 2);
189         setMinimumSize(thisRect.width(), thisRect.height());
190
191         //Enable buttons
192         connect(ui->button_AbortProcess, SIGNAL(clicked()), this, SLOT(abortEncoding()));
193         
194         //Init progress indicator
195         m_progressIndicator = new QMovie(":/images/Working.gif");
196         m_progressIndicator->setCacheMode(QMovie::CacheAll);
197         ui->label_headerWorking->setMovie(m_progressIndicator);
198         ui->progressBar->setValue(0);
199
200         //Init progress model
201         m_progressModel = new ProgressModel();
202         ui->view_log->setModel(m_progressModel);
203         ui->view_log->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
204         ui->view_log->verticalHeader()->hide();
205         ui->view_log->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);
206         ui->view_log->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
207         ui->view_log->viewport()->installEventFilter(this);
208         connect(m_progressModel, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(progressModelChanged()));
209         connect(m_progressModel, SIGNAL(rowsMoved(QModelIndex,int,int,QModelIndex,int)), this, SLOT(progressModelChanged()));
210         connect(m_progressModel, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(progressModelChanged()));
211         connect(m_progressModel, SIGNAL(modelReset()), this, SLOT(progressModelChanged()));
212         connect(ui->view_log, SIGNAL(activated(QModelIndex)), this, SLOT(logViewDoubleClicked(QModelIndex)));
213         connect(ui->view_log->horizontalHeader(), SIGNAL(sectionResized(int,int,int)), this, SLOT(logViewSectionSizeChanged(int,int,int)));
214
215         //Create context menu
216         m_contextMenu = new QMenu();
217         QAction *contextMenuDetailsAction = m_contextMenu->addAction(QIcon(":/icons/zoom.png"), tr("Show details for selected job"));
218         QAction *contextMenuShowFileAction = m_contextMenu->addAction(QIcon(":/icons/folder_go.png"), tr("Browse Output File Location"));
219         m_contextMenu->addSeparator();
220
221         //Create "filter" context menu
222         m_progressViewFilterGroup = new QActionGroup(this);
223         QAction *contextMenuFilterAction[5] = {NULL, NULL, NULL, NULL, NULL};
224         if(QMenu *filterMenu = m_contextMenu->addMenu(QIcon(":/icons/filter.png"), tr("Filter Log Items")))
225         {
226                 contextMenuFilterAction[0] = filterMenu->addAction(m_progressModel->getIcon(ProgressModel::JobRunning), tr("Show Running Only"));
227                 contextMenuFilterAction[1] = filterMenu->addAction(m_progressModel->getIcon(ProgressModel::JobComplete), tr("Show Succeeded Only"));
228                 contextMenuFilterAction[2] = filterMenu->addAction(m_progressModel->getIcon(ProgressModel::JobFailed), tr("Show Failed Only"));
229                 contextMenuFilterAction[3] = filterMenu->addAction(m_progressModel->getIcon(ProgressModel::JobSkipped), tr("Show Skipped Only"));
230                 contextMenuFilterAction[4] = filterMenu->addAction(m_progressModel->getIcon(ProgressModel::JobState(-1)), tr("Show All Items"));
231                 if(QAction *act = contextMenuFilterAction[0]) { m_progressViewFilterGroup->addAction(act); act->setCheckable(true); act->setData(ProgressModel::JobRunning); }
232                 if(QAction *act = contextMenuFilterAction[1]) { m_progressViewFilterGroup->addAction(act); act->setCheckable(true); act->setData(ProgressModel::JobComplete); }
233                 if(QAction *act = contextMenuFilterAction[2]) { m_progressViewFilterGroup->addAction(act); act->setCheckable(true); act->setData(ProgressModel::JobFailed); }
234                 if(QAction *act = contextMenuFilterAction[3]) { m_progressViewFilterGroup->addAction(act); act->setCheckable(true); act->setData(ProgressModel::JobSkipped); }
235                 if(QAction *act = contextMenuFilterAction[4]) { m_progressViewFilterGroup->addAction(act); act->setCheckable(true); act->setData(-1); act->setChecked(true); }
236         }
237
238         //Create info label
239         if(m_filterInfoLabel = new QLabel(ui->view_log))
240         {
241                 m_filterInfoLabel->setFrameShape(QFrame::NoFrame);
242                 m_filterInfoLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
243                 m_filterInfoLabel->setUserData(0, new IntUserData(-1));
244                 SET_FONT_BOLD(m_filterInfoLabel, true);
245                 SET_TEXT_COLOR(m_filterInfoLabel, Qt::darkGray);
246                 m_filterInfoLabel->setContextMenuPolicy(Qt::CustomContextMenu);
247                 connect(m_filterInfoLabel, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenuTriggered(QPoint)));
248                 m_filterInfoLabel->hide();
249         }
250         if(m_filterInfoLabelIcon = new QLabel(ui->view_log))
251         {
252                 m_filterInfoLabelIcon->setFrameShape(QFrame::NoFrame);
253                 m_filterInfoLabelIcon->setAlignment(Qt::AlignHCenter | Qt::AlignTop);
254                 m_filterInfoLabelIcon->setContextMenuPolicy(Qt::CustomContextMenu);
255                 const QIcon &ico = m_progressModel->getIcon(ProgressModel::JobState(-1));
256                 m_filterInfoLabelIcon->setPixmap(ico.pixmap(16, 16));
257                 connect(m_filterInfoLabelIcon, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenuTriggered(QPoint)));
258                 m_filterInfoLabelIcon->hide();
259         }
260
261         //Connect context menu
262         ui->view_log->setContextMenuPolicy(Qt::CustomContextMenu);
263         connect(ui->view_log, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenuTriggered(QPoint)));
264         connect(contextMenuDetailsAction, SIGNAL(triggered(bool)), this, SLOT(contextMenuDetailsActionTriggered()));
265         connect(contextMenuShowFileAction, SIGNAL(triggered(bool)), this, SLOT(contextMenuShowFileActionTriggered()));
266         for(size_t i = 0; i < 5; i++)
267         {
268                 if(contextMenuFilterAction[i]) connect(contextMenuFilterAction[i], SIGNAL(triggered(bool)), this, SLOT(contextMenuFilterActionTriggered()));
269         }
270         SET_FONT_BOLD(contextMenuDetailsAction, true);
271
272         //Enque jobs
273         if(fileListModel)
274         {
275                 for(int i = 0; i < fileListModel->rowCount(); i++)
276                 {
277                         m_pendingJobs.append(fileListModel->getFile(fileListModel->index(i,0)));
278                 }
279         }
280
281         //Translate
282         ui->label_headerStatus->setText(QString("<b>%1</b><br>%2").arg(tr("Encoding Files"), tr("Your files are being encoded, please be patient...")));
283         
284         //Enable system tray icon
285         connect(m_systemTray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(systemTrayActivated(QSystemTrayIcon::ActivationReason)));
286
287         //Init other vars
288         m_runningThreads = 0;
289         m_currentFile = 0;
290         m_allJobs.clear();
291         m_succeededJobs.clear();
292         m_failedJobs.clear();
293         m_skippedJobs.clear();
294         m_userAborted = false;
295         m_forcedAbort = false;
296 }
297
298 ////////////////////////////////////////////////////////////
299 // Destructor
300 ////////////////////////////////////////////////////////////
301
302 ProcessingDialog::~ProcessingDialog(void)
303 {
304         ui->view_log->setModel(NULL);
305
306         if(m_progressIndicator)
307         {
308                 m_progressIndicator->stop();
309         }
310
311         if(m_diskObserver)
312         {
313                 m_diskObserver->stop();
314                 if(!m_diskObserver->wait(15000))
315                 {
316                         m_diskObserver->terminate();
317                         m_diskObserver->wait();
318                 }
319         }
320
321         if(m_cpuObserver)
322         {
323                 m_cpuObserver->stop();
324                 if(!m_cpuObserver->wait(15000))
325                 {
326                         m_cpuObserver->terminate();
327                         m_cpuObserver->wait();
328                 }
329         }
330
331         if(m_ramObserver)
332         {
333                 m_ramObserver->stop();
334                 if(!m_ramObserver->wait(15000))
335                 {
336                         m_ramObserver->terminate();
337                         m_ramObserver->wait();
338                 }
339         }
340
341         if(m_threadPool)
342         {
343                 if(!m_threadPool->waitForDone(100))
344                 {
345                         emit abortRunningTasks();
346                         m_threadPool->waitForDone();
347                 }
348         }
349
350         MUTILS_DELETE(m_progressIndicator);
351         MUTILS_DELETE(m_systemTray);
352         MUTILS_DELETE(m_diskObserver);
353         MUTILS_DELETE(m_cpuObserver);
354         MUTILS_DELETE(m_ramObserver);
355         MUTILS_DELETE(m_progressViewFilterGroup);
356         MUTILS_DELETE(m_filterInfoLabel);
357         MUTILS_DELETE(m_filterInfoLabelIcon);
358         MUTILS_DELETE(m_contextMenu);
359         MUTILS_DELETE(m_progressModel);
360         MUTILS_DELETE(m_threadPool);
361         MUTILS_DELETE(m_defaultColor);
362
363         WinSevenTaskbar::setOverlayIcon(this, NULL);
364         WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNoState);
365         
366         MUTILS_DELETE(ui);
367 }
368
369 ////////////////////////////////////////////////////////////
370 // EVENTS
371 ////////////////////////////////////////////////////////////
372
373 void ProcessingDialog::showEvent(QShowEvent *event)
374 {
375         QDialog::showEvent(event);
376
377         if(m_firstShow)
378         {
379                 static const char *NA = " N/A";
380
381                 MUtils::GUI::enable_close_button(this, false);
382                 ui->button_closeDialog->setEnabled(false);
383                 ui->button_AbortProcess->setEnabled(false);
384                 m_progressIndicator->start();
385                 m_systemTray->setVisible(true);
386                 
387                 MUtils::OS::change_process_priority(1);
388                 
389                 ui->label_cpu->setText(NA);
390                 ui->label_disk->setText(NA);
391                 ui->label_ram->setText(NA);
392
393                 QTimer::singleShot(500, this, SLOT(initEncoding()));
394                 m_firstShow = false;
395         }
396
397         //Force update geometry
398         resizeEvent(NULL);
399 }
400
401 void ProcessingDialog::closeEvent(QCloseEvent *event)
402 {
403         if(!ui->button_closeDialog->isEnabled())
404         {
405                 event->ignore();
406         }
407         else
408         {
409                 m_systemTray->setVisible(false);
410         }
411 }
412
413 bool ProcessingDialog::eventFilter(QObject *obj, QEvent *event)
414 {
415         if(obj == ui->label_versionInfo)
416         {
417                 if(event->type() == QEvent::Enter)
418                 {
419                         QPalette palette = ui->label_versionInfo->palette();
420                         *m_defaultColor = palette.color(QPalette::Normal, QPalette::WindowText);
421                         palette.setColor(QPalette::Normal, QPalette::WindowText, Qt::red);
422                         ui->label_versionInfo->setPalette(palette);
423                 }
424                 else if(event->type() == QEvent::Leave)
425                 {
426                         QPalette palette = ui->label_versionInfo->palette();
427                         palette.setColor(QPalette::Normal, QPalette::WindowText, *m_defaultColor);
428                         ui->label_versionInfo->setPalette(palette);
429                 }
430                 else if(event->type() == QEvent::MouseButtonPress)
431                 {
432                         QUrl url(lamexp_website_url());
433                         QDesktopServices::openUrl(url);
434                 }
435         }
436
437         return false;
438 }
439
440 bool ProcessingDialog::event(QEvent *e)
441 {
442         switch(e->type())
443         {
444         case MUtils::GUI::USER_EVENT_QUERYENDSESSION:
445                 qWarning("System is shutting down, preparing to abort...");
446                 if(!m_userAborted) abortEncoding(true);
447                 return true;
448         case MUtils::GUI::USER_EVENT_ENDSESSION:
449                 qWarning("System is shutting down, encoding will be aborted now...");
450                 if(isVisible())
451                 {
452                         while(!close())
453                         {
454                                 if(!m_userAborted) abortEncoding(true);
455                                 qApp->processEvents(QEventLoop::WaitForMoreEvents | QEventLoop::ExcludeUserInputEvents);
456                         }
457                 }
458                 m_pendingJobs.clear();
459                 return true;
460         default:
461                 return QDialog::event(e);
462         }
463 }
464
465 /*
466  * Window was resized
467  */
468 void ProcessingDialog::resizeEvent(QResizeEvent *event)
469 {
470         if(event) QDialog::resizeEvent(event);
471
472         if(QWidget *port = ui->view_log->viewport())
473         {
474                 QRect geom = port->geometry();
475                 m_filterInfoLabel->setGeometry(geom.left() + 16, geom.top() + 16, geom.width() - 32, 48);
476                 m_filterInfoLabelIcon->setGeometry(geom.left() + 16, geom.top() + 64, geom.width() - 32, geom.height() - 80);
477         }
478 }
479
480 bool ProcessingDialog::winEvent(MSG *message, long *result)
481 {
482         return WinSevenTaskbar::handleWinEvent(message, result);
483 }
484
485 ////////////////////////////////////////////////////////////
486 // SLOTS
487 ////////////////////////////////////////////////////////////
488
489 void ProcessingDialog::initEncoding(void)
490 {
491         qDebug("Initializing encoding process...");
492         
493         m_runningThreads = 0;
494         m_currentFile = 0;
495         m_allJobs.clear();
496         m_succeededJobs.clear();
497         m_failedJobs.clear();
498         m_skippedJobs.clear();
499         m_userAborted = false;
500         m_forcedAbort = false;
501         m_playList.clear();
502
503         DecoderRegistry::configureDecoders(m_settings);
504
505         CHANGE_BACKGROUND_COLOR(ui->frame_header, QColor(Qt::white));
506         SET_PROGRESS_TEXT(tr("Encoding files, please wait..."));
507         
508         ui->button_closeDialog->setEnabled(false);
509         ui->button_AbortProcess->setEnabled(true);
510         ui->progressBar->setRange(0, m_pendingJobs.count());
511         ui->checkBox_shutdownComputer->setEnabled(true);
512         ui->checkBox_shutdownComputer->setChecked(false);
513
514         WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
515         WinSevenTaskbar::setTaskbarProgress(this, 0, m_pendingJobs.count());
516         WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/control_play_blue.png"));
517
518         if(!m_diskObserver)
519         {
520                 m_diskObserver = new DiskObserverThread(m_settings->customTempPathEnabled() ? m_settings->customTempPath() : MUtils::temp_folder());
521                 connect(m_diskObserver, SIGNAL(messageLogged(QString,int)), m_progressModel, SLOT(addSystemMessage(QString,int)), Qt::QueuedConnection);
522                 connect(m_diskObserver, SIGNAL(freeSpaceChanged(quint64)), this, SLOT(diskUsageHasChanged(quint64)), Qt::QueuedConnection);
523                 m_diskObserver->start();
524         }
525         if(!m_cpuObserver)
526         {
527                 m_cpuObserver = new CPUObserverThread();
528                 connect(m_cpuObserver, SIGNAL(currentUsageChanged(double)), this, SLOT(cpuUsageHasChanged(double)), Qt::QueuedConnection);
529                 m_cpuObserver->start();
530         }
531         if(!m_ramObserver)
532         {
533                 m_ramObserver = new RAMObserverThread();
534                 connect(m_ramObserver, SIGNAL(currentUsageChanged(double)), this, SLOT(ramUsageHasChanged(double)), Qt::QueuedConnection);
535                 m_ramObserver->start();
536         }
537
538         if(!m_threadPool)
539         {
540                 unsigned int maximumInstances = qBound(0U, m_settings->maximumInstances(), MAX_INSTANCES);
541                 if(maximumInstances < 1)
542                 {
543                         const MUtils::CPUFetaures::cpu_info_t cpuFeatures = MUtils::CPUFetaures::detect(MUtils::OS::arguments());
544                         maximumInstances = cores2instances(qBound(1U, cpuFeatures.count, 64U));
545                 }
546
547                 maximumInstances = qBound(1U, maximumInstances, static_cast<unsigned int>(m_pendingJobs.count()));
548                 if(maximumInstances > 1)
549                 {
550                         m_progressModel->addSystemMessage(tr("Multi-threading enabled: Running %1 instances in parallel!").arg(QString::number(maximumInstances)));
551                 }
552
553                 m_threadPool = new QThreadPool();
554                 m_threadPool->setMaxThreadCount(maximumInstances);
555         }
556
557         m_initThreads = m_threadPool->maxThreadCount();
558         QTimer::singleShot(100, this, SLOT(initNextJob()));
559         
560         m_totalTime.reset(new QElapsedTimer());
561         m_totalTime->start();
562 }
563
564 void ProcessingDialog::initNextJob(void)
565 {
566         if((m_initThreads > 0) && (!m_userAborted))
567         {
568                 startNextJob();
569                 if(--m_initThreads > 0)
570                 {
571                         QTimer::singleShot(32, this, SLOT(initNextJob()));
572                 }
573         }
574 }
575
576 void ProcessingDialog::startNextJob(void)
577 {
578         if(m_pendingJobs.isEmpty())
579         {
580                 qWarning("No more files left, unable to start another job!");
581                 return;
582         }
583         
584         m_currentFile++;
585         m_runningThreads++;
586
587         AudioFileModel currentFile = updateMetaInfo(m_pendingJobs.takeFirst());
588         bool nativeResampling = false;
589
590         //Create encoder instance
591         AbstractEncoder *encoder = EncoderRegistry::createInstance(m_settings->compressionEncoder(), m_settings, &nativeResampling);
592
593         //Create processing thread
594         ProcessThread *thread = new ProcessThread
595         (
596                 currentFile,
597                 (m_settings->outputToSourceDir() ? QFileInfo(currentFile.filePath()).absolutePath() : m_settings->outputDir()),
598                 (m_settings->customTempPathEnabled() ? m_settings->customTempPath() : MUtils::temp_folder()),
599                 encoder,
600                 m_settings->prependRelativeSourcePath() && (!m_settings->outputToSourceDir())
601         );
602
603         //Add audio filters
604         if(m_settings->forceStereoDownmix())
605         {
606                 thread->addFilter(new DownmixFilter());
607         }
608         if((m_settings->samplingRate() > 0) && !nativeResampling)
609         {
610                 if(SettingsModel::samplingRates[m_settings->samplingRate()] != currentFile.techInfo().audioSamplerate() || currentFile.techInfo().audioSamplerate() == 0)
611                 {
612                         thread->addFilter(new ResampleFilter(SettingsModel::samplingRates[m_settings->samplingRate()]));
613                 }
614         }
615         if((m_settings->toneAdjustBass() != 0) || (m_settings->toneAdjustTreble() != 0))
616         {
617                 thread->addFilter(new ToneAdjustFilter(m_settings->toneAdjustBass(), m_settings->toneAdjustTreble()));
618         }
619         if(m_settings->normalizationFilterEnabled())
620         {
621                 thread->addFilter(new NormalizeFilter(m_settings->normalizationFilterMaxVolume(), m_settings->normalizationFilterEQMode()));
622         }
623         if(m_settings->renameOutputFilesEnabled() && (!m_settings->renameOutputFilesPattern().simplified().isEmpty()))
624         {
625                 thread->setRenamePattern(m_settings->renameOutputFilesPattern());
626         }
627         if(m_settings->overwriteMode() != SettingsModel::Overwrite_KeepBoth)
628         {
629                 thread->setOverwriteMode((m_settings->overwriteMode() == SettingsModel::Overwrite_SkipFile), (m_settings->overwriteMode() == SettingsModel::Overwrite_Replaces));
630         }
631
632         m_allJobs.append(thread->getId());
633         
634         //Connect thread signals
635         connect(thread, SIGNAL(processFinished()), this, SLOT(doneEncoding()), Qt::QueuedConnection);
636         connect(thread, SIGNAL(processStateInitialized(QUuid,QString,QString,int)), m_progressModel, SLOT(addJob(QUuid,QString,QString,int)), Qt::QueuedConnection);
637         connect(thread, SIGNAL(processStateChanged(QUuid,QString,int)), m_progressModel, SLOT(updateJob(QUuid,QString,int)), Qt::QueuedConnection);
638         connect(thread, SIGNAL(processStateFinished(QUuid,QString,int)), this, SLOT(processFinished(QUuid,QString,int)), Qt::QueuedConnection);
639         connect(thread, SIGNAL(processMessageLogged(QUuid,QString)), m_progressModel, SLOT(appendToLog(QUuid,QString)), Qt::QueuedConnection);
640         connect(this, SIGNAL(abortRunningTasks()), thread, SLOT(abort()), Qt::DirectConnection);
641
642         //Initialize thread object
643         if(!thread->init())
644         {
645                 qFatal("Fatal Error: Thread initialization has failed!");
646         }
647
648         //Give it a go!
649         if(!thread->start(m_threadPool))
650         {
651                 qWarning("Job failed to start or file was skipped!");
652         }
653 }
654
655 void ProcessingDialog::abortEncoding(bool force)
656 {
657         m_userAborted = true;
658         if(force) m_forcedAbort = true;
659         ui->button_AbortProcess->setEnabled(false);
660         SET_PROGRESS_TEXT(tr("Aborted! Waiting for running jobs to terminate..."));
661         emit abortRunningTasks();
662 }
663
664 void ProcessingDialog::doneEncoding(void)
665 {
666         m_runningThreads--;
667         ui->progressBar->setValue(ui->progressBar->value() + 1);
668         
669         if(!m_userAborted)
670         {
671                 SET_PROGRESS_TEXT(tr("Encoding: %n file(s) of %1 completed so far, please wait...", "", ui->progressBar->value()).arg(QString::number(ui->progressBar->maximum())));
672                 WinSevenTaskbar::setTaskbarProgress(this, ui->progressBar->value(), ui->progressBar->maximum());
673         }
674         
675         if((!m_pendingJobs.isEmpty()) && (!m_userAborted))
676         {
677                 QTimer::singleShot(0, this, SLOT(startNextJob()));
678                 qDebug("%d files left, starting next job...", m_pendingJobs.count());
679                 return;
680         }
681         
682         if(m_runningThreads > 0)
683         {
684                 qDebug("No files left, but still have %u running jobs.", m_runningThreads);
685                 return;
686         }
687
688         QApplication::setOverrideCursor(Qt::WaitCursor);
689         qDebug("Running jobs: %u", m_runningThreads);
690
691         if(!m_userAborted && m_settings->createPlaylist() && !m_settings->outputToSourceDir())
692         {
693                 SET_PROGRESS_TEXT(tr("Creating the playlist file, please wait..."));
694                 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
695                 writePlayList();
696         }
697         
698         if(m_userAborted)
699         {
700                 CHANGE_BACKGROUND_COLOR(ui->frame_header, QColor("#FFFFE0"));
701                 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
702                 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/error.png"));
703                 SET_PROGRESS_TEXT((m_succeededJobs.count() > 0) ? tr("Process was aborted by the user after %n file(s)!", "", m_succeededJobs.count()) : tr("Process was aborted prematurely by the user!"));
704                 m_systemTray->showMessage(tr("LameXP - Aborted"), tr("Process was aborted by the user."), QSystemTrayIcon::Warning);
705                 m_systemTray->setIcon(QIcon(":/icons/cd_delete.png"));
706                 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
707                 if(!m_forcedAbort) PLAY_SOUND_OPTIONAL("aborted", false);
708         }
709         else
710         {
711                 if((!m_totalTime.isNull()) && m_totalTime->isValid())
712                 {
713                         m_progressModel->addSystemMessage(tr("Process finished after %1.").arg(time2text(m_totalTime->elapsed())), ProgressModel::SysMsg_Performance);
714                         m_totalTime->invalidate();
715                 }
716
717                 if(m_failedJobs.count() > 0)
718                 {
719                         CHANGE_BACKGROUND_COLOR(ui->frame_header, QColor("#FFF0F0"));
720                         WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
721                         WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/exclamation.png"));
722                         if(m_skippedJobs.count() > 0)
723                         {
724                                 SET_PROGRESS_TEXT(tr("Error: %1 of %n file(s) failed (%2). Double-click failed items for detailed information!", "", m_failedJobs.count() + m_succeededJobs.count() + m_skippedJobs.count()).arg(QString::number(m_failedJobs.count()), tr("%n file(s) skipped", "", m_skippedJobs.count())));
725                         }
726                         else
727                         {
728                                 SET_PROGRESS_TEXT(tr("Error: %1 of %n file(s) failed. Double-click failed items for detailed information!", "", m_failedJobs.count() + m_succeededJobs.count()).arg(QString::number(m_failedJobs.count())));
729                         }
730                         m_systemTray->showMessage(tr("LameXP - Error"), tr("At least one file has failed!"), QSystemTrayIcon::Critical);
731                         m_systemTray->setIcon(QIcon(":/icons/cd_delete.png"));
732                         qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
733                         PLAY_SOUND_OPTIONAL("error", false);
734                 }
735                 else
736                 {
737                         CHANGE_BACKGROUND_COLOR(ui->frame_header, QColor("#F0FFF0"));
738                         WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
739                         WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/accept.png"));
740                         if(m_skippedJobs.count() > 0)
741                         {
742                                 SET_PROGRESS_TEXT(tr("All files completed successfully. Skipped %n file(s).", "", m_skippedJobs.count()));
743                         }
744                         else
745                         {
746                                 SET_PROGRESS_TEXT(tr("All files completed successfully."));
747                         }
748                         m_systemTray->showMessage(tr("LameXP - Done"), tr("All files completed successfully."), QSystemTrayIcon::Information);
749                         m_systemTray->setIcon(QIcon(":/icons/cd_add.png"));
750                         qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
751                         PLAY_SOUND_OPTIONAL("success", false);
752                 }
753         }
754         
755         MUtils::GUI::enable_close_button(this, true);
756         ui->button_closeDialog->setEnabled(true);
757         ui->button_AbortProcess->setEnabled(false);
758         ui->checkBox_shutdownComputer->setEnabled(false);
759
760         m_progressModel->restoreHiddenItems();
761         ui->view_log->scrollToBottom();
762         m_progressIndicator->stop();
763         ui->progressBar->setValue(ui->progressBar->maximum());
764         WinSevenTaskbar::setTaskbarProgress(this, ui->progressBar->value(), ui->progressBar->maximum());
765
766         QApplication::restoreOverrideCursor();
767
768         if(!m_userAborted && ui->checkBox_shutdownComputer->isChecked())
769         {
770                 if(shutdownComputer())
771                 {
772                         m_shutdownFlag = m_settings->hibernateComputer() ? shutdownFlag_Hibernate : shutdownFlag_TurnPowerOff;
773                         accept();
774                 }
775         }
776 }
777
778 void ProcessingDialog::processFinished(const QUuid &jobId, const QString &outFileName, int success)
779 {
780         if(success > 0)
781         {
782                 m_playList.insert(jobId, outFileName);
783                 m_succeededJobs.append(jobId);
784         }
785         else if(success < 0)
786         {
787                 m_playList.insert(jobId, outFileName);
788                 m_skippedJobs.append(jobId);
789         }
790         else
791         {
792                 m_failedJobs.append(jobId);
793         }
794
795         //Update filter as soon as a job finished!
796         if(m_progressViewFilter >= 0)
797         {
798                 QTimer::singleShot(0, this, SLOT(progressViewFilterChanged()));
799         }
800 }
801
802 void ProcessingDialog::progressModelChanged(void)
803 {
804         //Update filter as soon as the model changes!
805         if(m_progressViewFilter >= 0)
806         {
807                 QTimer::singleShot(0, this, SLOT(progressViewFilterChanged()));
808         }
809
810         QTimer::singleShot(0, ui->view_log, SLOT(scrollToBottom()));
811 }
812
813 void ProcessingDialog::logViewDoubleClicked(const QModelIndex &index)
814 {
815         if(m_runningThreads == 0)
816         {
817                 const QStringList &logFile = m_progressModel->getLogFile(index);
818                 
819                 if(!logFile.isEmpty())
820                 {
821                         LogViewDialog *logView = new LogViewDialog(this);
822                         logView->setWindowTitle(QString("LameXP - [%1]").arg(m_progressModel->data(index, Qt::DisplayRole).toString()));
823                         logView->exec(logFile);
824                         MUTILS_DELETE(logView);
825                 }
826                 else
827                 {
828                         QMessageBox::information(this, windowTitle(), m_progressModel->data(m_progressModel->index(index.row(), 0)).toString());
829                 }
830         }
831         else
832         {
833                 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN);
834         }
835 }
836
837 void ProcessingDialog::logViewSectionSizeChanged(int logicalIndex, int oldSize, int newSize)
838 {
839         if(logicalIndex == 1)
840         {
841                 if(QHeaderView *hdr = ui->view_log->horizontalHeader())
842                 {
843                         hdr->setMinimumSectionSize(qMax(hdr->minimumSectionSize(), hdr->sectionSize(1)));
844                 }
845         }
846 }
847
848 void ProcessingDialog::contextMenuTriggered(const QPoint &pos)
849 {
850         QAbstractScrollArea *scrollArea = dynamic_cast<QAbstractScrollArea*>(QObject::sender());
851         QWidget *sender = scrollArea ? scrollArea->viewport() : dynamic_cast<QWidget*>(QObject::sender());      
852
853         if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0)
854         {
855                 m_contextMenu->popup(sender->mapToGlobal(pos));
856         }
857 }
858
859 void ProcessingDialog::contextMenuDetailsActionTriggered(void)
860 {
861         QModelIndex index = ui->view_log->indexAt(ui->view_log->viewport()->mapFromGlobal(m_contextMenu->pos()));
862         logViewDoubleClicked(index.isValid() ? index : ui->view_log->currentIndex());
863 }
864
865 void ProcessingDialog::contextMenuShowFileActionTriggered(void)
866 {
867         QModelIndex index = ui->view_log->indexAt(ui->view_log->viewport()->mapFromGlobal(m_contextMenu->pos()));
868         const QUuid &jobId = m_progressModel->getJobId(index.isValid() ? index : ui->view_log->currentIndex());
869         QString filePath = m_playList.value(jobId, QString());
870
871         if(filePath.isEmpty())
872         {
873                 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN);
874                 return;
875         }
876
877         if(QFileInfo(filePath).exists())
878         {
879                 QString systemRootPath;
880
881                 QDir systemRoot(MUtils::OS::known_folder(MUtils::OS::FOLDER_SYSTEMFOLDER));
882                 if(systemRoot.exists() && systemRoot.cdUp())
883                 {
884                         systemRootPath = systemRoot.canonicalPath();
885                 }
886
887                 if(!systemRootPath.isEmpty())
888                 {
889                         QFileInfo explorer(QString("%1/explorer.exe").arg(systemRootPath));
890                         if(explorer.exists() && explorer.isFile())
891                         {
892                                 QProcess::execute(explorer.canonicalFilePath(), QStringList() << "/select," << QDir::toNativeSeparators(QFileInfo(filePath).canonicalFilePath()));
893                                 return;
894                         }
895                 }
896                 else
897                 {
898                         qWarning("SystemRoot directory could not be detected!");
899                 }
900         }
901         else
902         {
903                 qWarning("File not found: %s", filePath.toLatin1().constData());
904                 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
905         }
906 }
907
908 void ProcessingDialog::contextMenuFilterActionTriggered(void)
909 {
910         if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
911         {
912                 if(action->data().type() == QVariant::Int)
913                 {
914                         m_progressViewFilter = action->data().toInt();
915                         progressViewFilterChanged();
916                         QTimer::singleShot(0, this, SLOT(progressViewFilterChanged()));
917                         QTimer::singleShot(0, ui->view_log, SLOT(scrollToBottom()));
918                         action->setChecked(true);
919                 }
920         }
921 }
922
923 /*
924  * Filter progress items
925  */
926 void ProcessingDialog::progressViewFilterChanged(void)
927 {
928         bool matchFound = false;
929
930         for(int i = 0; i < ui->view_log->model()->rowCount(); i++)
931         {
932                 QModelIndex index = (m_progressViewFilter >= 0) ? m_progressModel->index(i, 0) : QModelIndex();
933                 const bool bHide = index.isValid() ? (m_progressModel->getJobState(index) != m_progressViewFilter) : false;
934                 ui->view_log->setRowHidden(i, bHide); matchFound = matchFound || (!bHide);
935         }
936
937         if((m_progressViewFilter >= 0) && (!matchFound))
938         {
939                 if(m_filterInfoLabel->isHidden() || (dynamic_cast<IntUserData*>(m_filterInfoLabel->userData(0))->value() != m_progressViewFilter))
940                 {
941                         dynamic_cast<IntUserData*>(m_filterInfoLabel->userData(0))->setValue(m_progressViewFilter);
942                         m_filterInfoLabel->setText(QString("<p>&raquo; %1 &laquo;</p>").arg(tr("None of the items matches the current filtering rules")));
943                         m_filterInfoLabel->show();
944                         m_filterInfoLabelIcon->setPixmap(m_progressModel->getIcon(static_cast<ProgressModel::JobState>(m_progressViewFilter)).pixmap(16, 16, QIcon::Disabled));
945                         m_filterInfoLabelIcon->show();
946                         resizeEvent(NULL);
947                 }
948         }
949         else if(!m_filterInfoLabel->isHidden())
950         {
951                 m_filterInfoLabel->hide();
952                 m_filterInfoLabelIcon->hide();
953         }
954 }
955
956 ////////////////////////////////////////////////////////////
957 // Private Functions
958 ////////////////////////////////////////////////////////////
959
960 void ProcessingDialog::writePlayList(void)
961 {
962         if(m_succeededJobs.count() <= 0 || m_allJobs.count() <= 0)
963         {
964                 qWarning("WritePlayList: Nothing to do!");
965                 return;
966         }
967         
968         //Init local variables
969         QStringList list;
970         QRegExp regExp1("\\[\\d\\d\\][^/\\\\]+$", Qt::CaseInsensitive);
971         QRegExp regExp2("\\(\\d\\d\\)[^/\\\\]+$", Qt::CaseInsensitive);
972         QRegExp regExp3("\\d\\d[^/\\\\]+$", Qt::CaseInsensitive);
973         bool usePrefix[3] = {true, true, true};
974         bool useUtf8 = false;
975         int counter = 1;
976
977         //Generate playlist name
978         QString playListName = (m_metaInfo->album().isEmpty() ? "Playlist" : m_metaInfo->album());
979         if(!m_metaInfo->artist().isEmpty())
980         {
981                 playListName = QString("%1 - %2").arg(m_metaInfo->artist(), playListName);
982         }
983
984         //Clean playlist name
985         playListName = MUtils::clean_file_name(playListName);
986
987         //Create list of audio files
988         for(int i = 0; i < m_allJobs.count(); i++)
989         {
990                 if(!m_succeededJobs.contains(m_allJobs.at(i))) continue;
991                 list << QDir::toNativeSeparators(QDir(m_settings->outputDir()).relativeFilePath(m_playList.value(m_allJobs.at(i), "N/A")));
992         }
993
994         //Use prefix?
995         for(int i = 0; i < list.count(); i++)
996         {
997                 if(regExp1.indexIn(list.at(i)) < 0) usePrefix[0] = false;
998                 if(regExp2.indexIn(list.at(i)) < 0) usePrefix[1] = false;
999                 if(regExp3.indexIn(list.at(i)) < 0) usePrefix[2] = false;
1000         }
1001         if(usePrefix[0] || usePrefix[1] || usePrefix[2])
1002         {
1003                 playListName.prepend(usePrefix[0] ? "[00] " : (usePrefix[1] ? "(00) " : "00 "));
1004         }
1005
1006         //Do we need an UTF-8 playlist?
1007         for(int i = 0; i < list.count(); i++)
1008         {
1009                 if(wcscmp(MUTILS_WCHR(QString::fromLatin1(list.at(i).toLatin1().constData())), MUTILS_WCHR(list.at(i))))
1010                 {
1011                         useUtf8 = true;
1012                         break;
1013                 }
1014         }
1015
1016         //Generate playlist output file
1017         QString playListFile = QString("%1/%2.%3").arg(m_settings->outputDir(), playListName, (useUtf8 ? "m3u8" : "m3u"));
1018         while(QFileInfo(playListFile).exists())
1019         {
1020                 playListFile = QString("%1/%2 (%3).%4").arg(m_settings->outputDir(), playListName, QString::number(++counter), (useUtf8 ? "m3u8" : "m3u"));
1021         }
1022
1023         //Now write playlist to output file
1024         QFile playList(playListFile);
1025         if(playList.open(QIODevice::WriteOnly))
1026         {
1027                 if(useUtf8)
1028                 {
1029                         playList.write("\xef\xbb\xbf");
1030                 }
1031                 playList.write("#EXTM3U\r\n");
1032                 while(!list.isEmpty())
1033                 {
1034                         playList.write(useUtf8 ? MUTILS_UTF8(list.takeFirst()) : list.takeFirst().toLatin1().constData());
1035                         playList.write("\r\n");
1036                 }
1037                 playList.close();
1038         }
1039         else
1040         {
1041                 QMessageBox::warning(this, tr("Playlist creation failed"), QString("%1<br><nobr>%2</nobr>").arg(tr("The playlist file could not be created:"), playListFile));
1042         }
1043 }
1044
1045 AudioFileModel ProcessingDialog::updateMetaInfo(AudioFileModel &audioFile)
1046 {
1047         if(!m_settings->writeMetaTags())
1048         {
1049                 audioFile.metaInfo().reset();
1050                 return audioFile;
1051         }
1052         
1053         audioFile.metaInfo().update(*m_metaInfo, true);
1054         
1055         if(audioFile.metaInfo().position() == UINT_MAX)
1056         {
1057                 audioFile.metaInfo().setPosition(m_currentFile);
1058         }
1059
1060         return audioFile;
1061 }
1062
1063 void ProcessingDialog::systemTrayActivated(QSystemTrayIcon::ActivationReason reason)
1064 {
1065         if(reason == QSystemTrayIcon::DoubleClick)
1066         {
1067                 MUtils::GUI::bring_to_front(this);
1068         }
1069 }
1070
1071 void ProcessingDialog::cpuUsageHasChanged(const double val)
1072 {
1073         
1074         ui->label_cpu->setText(QString().sprintf(" %d%%", qRound(val * 100.0)));
1075         UPDATE_MIN_WIDTH(ui->label_cpu);
1076 }
1077
1078 void ProcessingDialog::ramUsageHasChanged(const double val)
1079 {
1080         
1081         ui->label_ram->setText(QString().sprintf(" %d%%", qRound(val * 100.0)));
1082         UPDATE_MIN_WIDTH(ui->label_ram);
1083 }
1084
1085 void ProcessingDialog::diskUsageHasChanged(const quint64 val)
1086 {
1087         int postfix = 0;
1088         const char *postfixStr[6] = {"B", "KB", "MB", "GB", "TB", "PB"};
1089         double space = static_cast<double>(val);
1090
1091         while((space >= 1000.0) && (postfix < 5))
1092         {
1093                 space = space / 1024.0;
1094                 postfix++;
1095         }
1096
1097         ui->label_disk->setText(QString().sprintf(" %3.1f %s", space, postfixStr[postfix]));
1098         UPDATE_MIN_WIDTH(ui->label_disk);
1099 }
1100
1101 bool ProcessingDialog::shutdownComputer(void)
1102 {
1103         const int iTimeout = m_settings->hibernateComputer() ? 10 : 30;
1104         const Qt::WindowFlags flags = Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowSystemMenuHint;
1105         const QString text = QString("%1%2%1").arg(QString().fill(' ', 18), tr("Warning: Computer will shutdown in %1 seconds..."));
1106         
1107         qWarning("Initiating shutdown sequence!");
1108         
1109         QProgressDialog progressDialog(text.arg(iTimeout), tr("Cancel Shutdown"), 0, iTimeout + 1, this, flags);
1110         QPushButton *cancelButton = new QPushButton(tr("Cancel Shutdown"), &progressDialog);
1111         cancelButton->setIcon(QIcon(":/icons/power_on.png"));
1112         progressDialog.setModal(true);
1113         progressDialog.setAutoClose(false);
1114         progressDialog.setAutoReset(false);
1115         progressDialog.setWindowIcon(QIcon(":/icons/power_off.png"));
1116         progressDialog.setCancelButton(cancelButton);
1117         progressDialog.show();
1118         
1119         qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1120
1121         QApplication::setOverrideCursor(Qt::WaitCursor);
1122         PLAY_SOUND_OPTIONAL("shutdown", false);
1123         QApplication::restoreOverrideCursor();
1124
1125         QTimer timer;
1126         timer.setInterval(1000);
1127         timer.start();
1128
1129         QEventLoop eventLoop(this);
1130         connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
1131         connect(&progressDialog, SIGNAL(canceled()), &eventLoop, SLOT(quit()));
1132
1133         for(int i = 1; i <= iTimeout; i++)
1134         {
1135                 eventLoop.exec();
1136                 if(progressDialog.wasCanceled())
1137                 {
1138                         progressDialog.close();
1139                         return false;
1140                 }
1141                 progressDialog.setValue(i+1);
1142                 progressDialog.setLabelText(text.arg(iTimeout-i));
1143                 if(iTimeout-i == 3) progressDialog.setCancelButton(NULL);
1144                 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1145                 PLAY_SOUND_OPTIONAL(((i < iTimeout) ? "beep" : "beep2"), false);
1146         }
1147         
1148         progressDialog.close();
1149         return true;
1150 }
1151
1152 QString ProcessingDialog::time2text(const qint64 &msec) const
1153 {
1154         const qint64 MILLISECONDS_PER_DAY = 86399999;   //24x60x60x1000 - 1
1155         const QTime time = QTime().addMSecs(qMin(msec, MILLISECONDS_PER_DAY));
1156
1157         QString a, b;
1158
1159         if(time.hour() > 0)
1160         {
1161                 a = tr("%n hour(s)",   "", time.hour());
1162                 b = tr("%n minute(s)", "", time.minute());
1163         }
1164         else if(time.minute() > 0)
1165         {
1166                 a = tr("%n minute(s)", "", time.minute());
1167                 b = tr("%n second(s)", "", time.second());
1168         }
1169         else
1170         {
1171                 a = tr("%n second(s)",      "", time.second());
1172                 b = tr("%n millisecond(s)", "", time.msec());
1173         }
1174
1175         return QString("%1, %2").arg(a, b);
1176 }
1177
1178 ////////////////////////////////////////////////////////////
1179 // HELPER FUNCTIONS
1180 ////////////////////////////////////////////////////////////
1181
1182 static int cores2instances(int cores)
1183 {
1184         //This function is a "cubic spline" with sampling points at:
1185         //(1,1); (2,2); (4,4); (8,6); (16,8); (32,11); (64,16)
1186         static const double LUT[8][5] =
1187         {
1188                 { 1.0,  0.014353554, -0.043060662, 1.028707108,  0.000000000},
1189                 { 2.0, -0.028707108,  0.215303309, 0.511979167,  0.344485294},
1190                 { 4.0,  0.010016468, -0.249379596, 2.370710784, -2.133823529},
1191                 { 8.0,  0.000282437, -0.015762868, 0.501776961,  2.850000000},
1192                 {16.0,  0.000033270, -0.003802849, 0.310416667,  3.870588235},
1193                 {32.0,  0.000006343, -0.001217831, 0.227696078,  4.752941176},
1194                 {64.0,  0.000000000,  0.000000000, 0.000000000, 16.000000000},
1195                 {DBL_MAX, 0.0, 0.0, 0.0, 0.0}
1196         };
1197
1198         double x = abs(static_cast<double>(cores)), y = 1.0;
1199         
1200         for(size_t i = 0; i < 7; i++)
1201         {
1202                 if((x >= LUT[i][0]) && (x < LUT[i+1][0]))
1203                 {
1204                         y = (((((LUT[i][1] * x) + LUT[i][2]) * x) + LUT[i][3]) * x) + LUT[i][4];
1205                         break;
1206                 }
1207         }
1208
1209         return qRound(y);
1210 }