OSDN Git Service

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