OSDN Git Service

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