OSDN Git Service

Moved more functions into MUtils library, especially all the Qt initialization code...
[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 16U
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                 lamexp_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         //for(int i = 0; i < m_threadPool->maxThreadCount(); i++)
563         //{
564         //      startNextJob();
565         //      qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
566         //      QThread::yieldCurrentThread();
567         //}
568
569         m_initThreads = m_threadPool->maxThreadCount();
570         QTimer::singleShot(100, this, SLOT(initNextJob()));
571         m_timerStart = lamexp_perfcounter_value();
572 }
573
574 void ProcessingDialog::initNextJob(void)
575 {
576         if((m_initThreads > 0) && (!m_userAborted))
577         {
578                 startNextJob();
579                 if(--m_initThreads > 0)
580                 {
581                         QTimer::singleShot(100, this, SLOT(initNextJob()));
582                 }
583         }
584 }
585
586 void ProcessingDialog::startNextJob(void)
587 {
588         if(m_pendingJobs.isEmpty())
589         {
590                 qWarning("No more files left, unable to start another job!");
591                 return;
592         }
593         
594         m_currentFile++;
595         m_runningThreads++;
596
597         AudioFileModel currentFile = updateMetaInfo(m_pendingJobs.takeFirst());
598         bool nativeResampling = false;
599
600         //Create encoder instance
601         AbstractEncoder *encoder = EncoderRegistry::createInstance(m_settings->compressionEncoder(), m_settings, &nativeResampling);
602
603         //Create processing thread
604         ProcessThread *thread = new ProcessThread
605         (
606                 currentFile,
607                 (m_settings->outputToSourceDir() ? QFileInfo(currentFile.filePath()).absolutePath() : m_settings->outputDir()),
608                 (m_settings->customTempPathEnabled() ? m_settings->customTempPath() : MUtils::temp_folder()),
609                 encoder,
610                 m_settings->prependRelativeSourcePath() && (!m_settings->outputToSourceDir())
611         );
612
613         //Add audio filters
614         if(m_settings->forceStereoDownmix())
615         {
616                 thread->addFilter(new DownmixFilter());
617         }
618         if((m_settings->samplingRate() > 0) && !nativeResampling)
619         {
620                 if(SettingsModel::samplingRates[m_settings->samplingRate()] != currentFile.techInfo().audioSamplerate() || currentFile.techInfo().audioSamplerate() == 0)
621                 {
622                         thread->addFilter(new ResampleFilter(SettingsModel::samplingRates[m_settings->samplingRate()]));
623                 }
624         }
625         if((m_settings->toneAdjustBass() != 0) || (m_settings->toneAdjustTreble() != 0))
626         {
627                 thread->addFilter(new ToneAdjustFilter(m_settings->toneAdjustBass(), m_settings->toneAdjustTreble()));
628         }
629         if(m_settings->normalizationFilterEnabled())
630         {
631                 thread->addFilter(new NormalizeFilter(m_settings->normalizationFilterMaxVolume(), m_settings->normalizationFilterEQMode()));
632         }
633         if(m_settings->renameOutputFilesEnabled() && (!m_settings->renameOutputFilesPattern().simplified().isEmpty()))
634         {
635                 thread->setRenamePattern(m_settings->renameOutputFilesPattern());
636         }
637         if(m_settings->overwriteMode() != SettingsModel::Overwrite_KeepBoth)
638         {
639                 thread->setOverwriteMode((m_settings->overwriteMode() == SettingsModel::Overwrite_SkipFile), (m_settings->overwriteMode() == SettingsModel::Overwrite_Replaces));
640         }
641
642         m_allJobs.append(thread->getId());
643         
644         //Connect thread signals
645         connect(thread, SIGNAL(processFinished()), this, SLOT(doneEncoding()), Qt::QueuedConnection);
646         connect(thread, SIGNAL(processStateInitialized(QUuid,QString,QString,int)), m_progressModel, SLOT(addJob(QUuid,QString,QString,int)), Qt::QueuedConnection);
647         connect(thread, SIGNAL(processStateChanged(QUuid,QString,int)), m_progressModel, SLOT(updateJob(QUuid,QString,int)), Qt::QueuedConnection);
648         connect(thread, SIGNAL(processStateFinished(QUuid,QString,int)), this, SLOT(processFinished(QUuid,QString,int)), Qt::QueuedConnection);
649         connect(thread, SIGNAL(processMessageLogged(QUuid,QString)), m_progressModel, SLOT(appendToLog(QUuid,QString)), Qt::QueuedConnection);
650         connect(this, SIGNAL(abortRunningTasks()), thread, SLOT(abort()), Qt::DirectConnection);
651
652         //Initialize thread object
653         if(!thread->init())
654         {
655                 qFatal("Fatal Error: Thread initialization has failed!");
656         }
657
658         //Give it a go!
659         if(!thread->start(m_threadPool))
660         {
661                 qWarning("Job failed to start or file was skipped!");
662         }
663 }
664
665 void ProcessingDialog::abortEncoding(bool force)
666 {
667         m_userAborted = true;
668         if(force) m_forcedAbort = true;
669         ui->button_AbortProcess->setEnabled(false);
670         SET_PROGRESS_TEXT(tr("Aborted! Waiting for running jobs to terminate..."));
671         emit abortRunningTasks();
672 }
673
674 void ProcessingDialog::doneEncoding(void)
675 {
676         m_runningThreads--;
677         ui->progressBar->setValue(ui->progressBar->value() + 1);
678         
679         if(!m_userAborted)
680         {
681                 SET_PROGRESS_TEXT(tr("Encoding: %n file(s) of %1 completed so far, please wait...", "", ui->progressBar->value()).arg(QString::number(ui->progressBar->maximum())));
682                 WinSevenTaskbar::setTaskbarProgress(this, ui->progressBar->value(), ui->progressBar->maximum());
683         }
684         
685         if((!m_pendingJobs.isEmpty()) && (!m_userAborted))
686         {
687                 QTimer::singleShot(0, this, SLOT(startNextJob()));
688                 qDebug("%d files left, starting next job...", m_pendingJobs.count());
689                 return;
690         }
691         
692         if(m_runningThreads > 0)
693         {
694                 qDebug("No files left, but still have %u running jobs.", m_runningThreads);
695                 return;
696         }
697
698         QApplication::setOverrideCursor(Qt::WaitCursor);
699         qDebug("Running jobs: %u", m_runningThreads);
700
701         if(!m_userAborted && m_settings->createPlaylist() && !m_settings->outputToSourceDir())
702         {
703                 SET_PROGRESS_TEXT(tr("Creating the playlist file, please wait..."));
704                 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
705                 writePlayList();
706         }
707         
708         if(m_userAborted)
709         {
710                 CHANGE_BACKGROUND_COLOR(ui->frame_header, QColor("#FFFFE0"));
711                 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
712                 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/error.png"));
713                 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!"));
714                 m_systemTray->showMessage(tr("LameXP - Aborted"), tr("Process was aborted by the user."), QSystemTrayIcon::Warning);
715                 m_systemTray->setIcon(QIcon(":/icons/cd_delete.png"));
716                 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
717                 if(!m_forcedAbort) PLAY_SOUND_OPTIONAL("aborted", false);
718         }
719         else
720         {
721                 const __int64 counter = lamexp_perfcounter_value();
722                 const __int64 frequency  = lamexp_perfcounter_frequ();
723                 if((counter >= 0I64) && (frequency >= 0))
724                 {
725                         if((m_timerStart >= 0I64) && (m_timerStart < counter))
726                         {
727                                 double timeElapsed = static_cast<double>(counter - m_timerStart) / static_cast<double>(frequency);
728                                 m_progressModel->addSystemMessage(tr("Process finished after %1.").arg(time2text(timeElapsed)), ProgressModel::SysMsg_Performance);
729                         }
730                 }
731
732                 if(m_failedJobs.count() > 0)
733                 {
734                         CHANGE_BACKGROUND_COLOR(ui->frame_header, QColor("#FFF0F0"));
735                         WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
736                         WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/exclamation.png"));
737                         if(m_skippedJobs.count() > 0)
738                         {
739                                 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())));
740                         }
741                         else
742                         {
743                                 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())));
744                         }
745                         m_systemTray->showMessage(tr("LameXP - Error"), tr("At least one file has failed!"), QSystemTrayIcon::Critical);
746                         m_systemTray->setIcon(QIcon(":/icons/cd_delete.png"));
747                         qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
748                         PLAY_SOUND_OPTIONAL("error", false);
749                 }
750                 else
751                 {
752                         CHANGE_BACKGROUND_COLOR(ui->frame_header, QColor("#F0FFF0"));
753                         WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
754                         WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/accept.png"));
755                         if(m_skippedJobs.count() > 0)
756                         {
757                                 SET_PROGRESS_TEXT(tr("All files completed successfully. Skipped %n file(s).", "", m_skippedJobs.count()));
758                         }
759                         else
760                         {
761                                 SET_PROGRESS_TEXT(tr("All files completed successfully."));
762                         }
763                         m_systemTray->showMessage(tr("LameXP - Done"), tr("All files completed successfully."), QSystemTrayIcon::Information);
764                         m_systemTray->setIcon(QIcon(":/icons/cd_add.png"));
765                         qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
766                         PLAY_SOUND_OPTIONAL("success", false);
767                 }
768         }
769         
770         lamexp_enable_close_button(this, true);
771         ui->button_closeDialog->setEnabled(true);
772         ui->button_AbortProcess->setEnabled(false);
773         ui->checkBox_shutdownComputer->setEnabled(false);
774
775         m_progressModel->restoreHiddenItems();
776         ui->view_log->scrollToBottom();
777         m_progressIndicator->stop();
778         ui->progressBar->setValue(ui->progressBar->maximum());
779         WinSevenTaskbar::setTaskbarProgress(this, ui->progressBar->value(), ui->progressBar->maximum());
780
781         QApplication::restoreOverrideCursor();
782
783         if(!m_userAborted && ui->checkBox_shutdownComputer->isChecked())
784         {
785                 if(shutdownComputer())
786                 {
787                         m_shutdownFlag = m_settings->hibernateComputer() ? shutdownFlag_Hibernate : shutdownFlag_TurnPowerOff;
788                         accept();
789                 }
790         }
791 }
792
793 void ProcessingDialog::processFinished(const QUuid &jobId, const QString &outFileName, int success)
794 {
795         if(success > 0)
796         {
797                 m_playList.insert(jobId, outFileName);
798                 m_succeededJobs.append(jobId);
799         }
800         else if(success < 0)
801         {
802                 m_playList.insert(jobId, outFileName);
803                 m_skippedJobs.append(jobId);
804         }
805         else
806         {
807                 m_failedJobs.append(jobId);
808         }
809
810         //Update filter as soon as a job finished!
811         if(m_progressViewFilter >= 0)
812         {
813                 QTimer::singleShot(0, this, SLOT(progressViewFilterChanged()));
814         }
815 }
816
817 void ProcessingDialog::progressModelChanged(void)
818 {
819         //Update filter as soon as the model changes!
820         if(m_progressViewFilter >= 0)
821         {
822                 QTimer::singleShot(0, this, SLOT(progressViewFilterChanged()));
823         }
824
825         QTimer::singleShot(0, ui->view_log, SLOT(scrollToBottom()));
826 }
827
828 void ProcessingDialog::logViewDoubleClicked(const QModelIndex &index)
829 {
830         if(m_runningThreads == 0)
831         {
832                 const QStringList &logFile = m_progressModel->getLogFile(index);
833                 
834                 if(!logFile.isEmpty())
835                 {
836                         LogViewDialog *logView = new LogViewDialog(this);
837                         logView->setWindowTitle(QString("LameXP - [%1]").arg(m_progressModel->data(index, Qt::DisplayRole).toString()));
838                         logView->exec(logFile);
839                         MUTILS_DELETE(logView);
840                 }
841                 else
842                 {
843                         QMessageBox::information(this, windowTitle(), m_progressModel->data(m_progressModel->index(index.row(), 0)).toString());
844                 }
845         }
846         else
847         {
848                 lamexp_beep(lamexp_beep_warning);
849         }
850 }
851
852 void ProcessingDialog::logViewSectionSizeChanged(int logicalIndex, int oldSize, int newSize)
853 {
854         if(logicalIndex == 1)
855         {
856                 if(QHeaderView *hdr = ui->view_log->horizontalHeader())
857                 {
858                         hdr->setMinimumSectionSize(qMax(hdr->minimumSectionSize(), hdr->sectionSize(1)));
859                 }
860         }
861 }
862
863 void ProcessingDialog::contextMenuTriggered(const QPoint &pos)
864 {
865         QAbstractScrollArea *scrollArea = dynamic_cast<QAbstractScrollArea*>(QObject::sender());
866         QWidget *sender = scrollArea ? scrollArea->viewport() : dynamic_cast<QWidget*>(QObject::sender());      
867
868         if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0)
869         {
870                 m_contextMenu->popup(sender->mapToGlobal(pos));
871         }
872 }
873
874 void ProcessingDialog::contextMenuDetailsActionTriggered(void)
875 {
876         QModelIndex index = ui->view_log->indexAt(ui->view_log->viewport()->mapFromGlobal(m_contextMenu->pos()));
877         logViewDoubleClicked(index.isValid() ? index : ui->view_log->currentIndex());
878 }
879
880 void ProcessingDialog::contextMenuShowFileActionTriggered(void)
881 {
882         QModelIndex index = ui->view_log->indexAt(ui->view_log->viewport()->mapFromGlobal(m_contextMenu->pos()));
883         const QUuid &jobId = m_progressModel->getJobId(index.isValid() ? index : ui->view_log->currentIndex());
884         QString filePath = m_playList.value(jobId, QString());
885
886         if(filePath.isEmpty())
887         {
888                 lamexp_beep(lamexp_beep_warning);
889                 return;
890         }
891
892         if(QFileInfo(filePath).exists())
893         {
894                 QString systemRootPath;
895
896                 QDir systemRoot(MUtils::OS::known_folder(MUtils::OS::FOLDER_SYSTEMFOLDER));
897                 if(systemRoot.exists() && systemRoot.cdUp())
898                 {
899                         systemRootPath = systemRoot.canonicalPath();
900                 }
901
902                 if(!systemRootPath.isEmpty())
903                 {
904                         QFileInfo explorer(QString("%1/explorer.exe").arg(systemRootPath));
905                         if(explorer.exists() && explorer.isFile())
906                         {
907                                 QProcess::execute(explorer.canonicalFilePath(), QStringList() << "/select," << QDir::toNativeSeparators(QFileInfo(filePath).canonicalFilePath()));
908                                 return;
909                         }
910                 }
911                 else
912                 {
913                         qWarning("SystemRoot directory could not be detected!");
914                 }
915         }
916         else
917         {
918                 qWarning("File not found: %s", filePath.toLatin1().constData());
919                 lamexp_beep(lamexp_beep_error);
920         }
921 }
922
923 void ProcessingDialog::contextMenuFilterActionTriggered(void)
924 {
925         if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
926         {
927                 if(action->data().type() == QVariant::Int)
928                 {
929                         m_progressViewFilter = action->data().toInt();
930                         progressViewFilterChanged();
931                         QTimer::singleShot(0, this, SLOT(progressViewFilterChanged()));
932                         QTimer::singleShot(0, ui->view_log, SLOT(scrollToBottom()));
933                         action->setChecked(true);
934                 }
935         }
936 }
937
938 /*
939  * Filter progress items
940  */
941 void ProcessingDialog::progressViewFilterChanged(void)
942 {
943         bool matchFound = false;
944
945         for(int i = 0; i < ui->view_log->model()->rowCount(); i++)
946         {
947                 QModelIndex index = (m_progressViewFilter >= 0) ? m_progressModel->index(i, 0) : QModelIndex();
948                 const bool bHide = index.isValid() ? (m_progressModel->getJobState(index) != m_progressViewFilter) : false;
949                 ui->view_log->setRowHidden(i, bHide); matchFound = matchFound || (!bHide);
950         }
951
952         if((m_progressViewFilter >= 0) && (!matchFound))
953         {
954                 if(m_filterInfoLabel->isHidden() || (dynamic_cast<IntUserData*>(m_filterInfoLabel->userData(0))->value() != m_progressViewFilter))
955                 {
956                         dynamic_cast<IntUserData*>(m_filterInfoLabel->userData(0))->setValue(m_progressViewFilter);
957                         m_filterInfoLabel->setText(QString("<p>&raquo; %1 &laquo;</p>").arg(tr("None of the items matches the current filtering rules")));
958                         m_filterInfoLabel->show();
959                         m_filterInfoLabelIcon->setPixmap(m_progressModel->getIcon(static_cast<ProgressModel::JobState>(m_progressViewFilter)).pixmap(16, 16, QIcon::Disabled));
960                         m_filterInfoLabelIcon->show();
961                         resizeEvent(NULL);
962                 }
963         }
964         else if(!m_filterInfoLabel->isHidden())
965         {
966                 m_filterInfoLabel->hide();
967                 m_filterInfoLabelIcon->hide();
968         }
969 }
970
971 ////////////////////////////////////////////////////////////
972 // Private Functions
973 ////////////////////////////////////////////////////////////
974
975 void ProcessingDialog::writePlayList(void)
976 {
977         if(m_succeededJobs.count() <= 0 || m_allJobs.count() <= 0)
978         {
979                 qWarning("WritePlayList: Nothing to do!");
980                 return;
981         }
982         
983         //Init local variables
984         QStringList list;
985         QRegExp regExp1("\\[\\d\\d\\][^/\\\\]+$", Qt::CaseInsensitive);
986         QRegExp regExp2("\\(\\d\\d\\)[^/\\\\]+$", Qt::CaseInsensitive);
987         QRegExp regExp3("\\d\\d[^/\\\\]+$", Qt::CaseInsensitive);
988         bool usePrefix[3] = {true, true, true};
989         bool useUtf8 = false;
990         int counter = 1;
991
992         //Generate playlist name
993         QString playListName = (m_metaInfo->album().isEmpty() ? "Playlist" : m_metaInfo->album());
994         if(!m_metaInfo->artist().isEmpty())
995         {
996                 playListName = QString("%1 - %2").arg(m_metaInfo->artist(), playListName);
997         }
998
999         //Clean playlist name
1000         playListName = lamexp_clean_filename(playListName);
1001
1002         //Create list of audio files
1003         for(int i = 0; i < m_allJobs.count(); i++)
1004         {
1005                 if(!m_succeededJobs.contains(m_allJobs.at(i))) continue;
1006                 list << QDir::toNativeSeparators(QDir(m_settings->outputDir()).relativeFilePath(m_playList.value(m_allJobs.at(i), "N/A")));
1007         }
1008
1009         //Use prefix?
1010         for(int i = 0; i < list.count(); i++)
1011         {
1012                 if(regExp1.indexIn(list.at(i)) < 0) usePrefix[0] = false;
1013                 if(regExp2.indexIn(list.at(i)) < 0) usePrefix[1] = false;
1014                 if(regExp3.indexIn(list.at(i)) < 0) usePrefix[2] = false;
1015         }
1016         if(usePrefix[0] || usePrefix[1] || usePrefix[2])
1017         {
1018                 playListName.prepend(usePrefix[0] ? "[00] " : (usePrefix[1] ? "(00) " : "00 "));
1019         }
1020
1021         //Do we need an UTF-8 playlist?
1022         for(int i = 0; i < list.count(); i++)
1023         {
1024                 if(wcscmp(MUTILS_WCHR(QString::fromLatin1(list.at(i).toLatin1().constData())), MUTILS_WCHR(list.at(i))))
1025                 {
1026                         useUtf8 = true;
1027                         break;
1028                 }
1029         }
1030
1031         //Generate playlist output file
1032         QString playListFile = QString("%1/%2.%3").arg(m_settings->outputDir(), playListName, (useUtf8 ? "m3u8" : "m3u"));
1033         while(QFileInfo(playListFile).exists())
1034         {
1035                 playListFile = QString("%1/%2 (%3).%4").arg(m_settings->outputDir(), playListName, QString::number(++counter), (useUtf8 ? "m3u8" : "m3u"));
1036         }
1037
1038         //Now write playlist to output file
1039         QFile playList(playListFile);
1040         if(playList.open(QIODevice::WriteOnly))
1041         {
1042                 if(useUtf8)
1043                 {
1044                         playList.write("\xef\xbb\xbf");
1045                 }
1046                 playList.write("#EXTM3U\r\n");
1047                 while(!list.isEmpty())
1048                 {
1049                         playList.write(useUtf8 ? MUTILS_UTF8(list.takeFirst()) : list.takeFirst().toLatin1().constData());
1050                         playList.write("\r\n");
1051                 }
1052                 playList.close();
1053         }
1054         else
1055         {
1056                 QMessageBox::warning(this, tr("Playlist creation failed"), QString("%1<br><nobr>%2</nobr>").arg(tr("The playlist file could not be created:"), playListFile));
1057         }
1058 }
1059
1060 AudioFileModel ProcessingDialog::updateMetaInfo(AudioFileModel &audioFile)
1061 {
1062         if(!m_settings->writeMetaTags())
1063         {
1064                 audioFile.metaInfo().reset();
1065                 return audioFile;
1066         }
1067         
1068         audioFile.metaInfo().update(*m_metaInfo, true);
1069         
1070         if(audioFile.metaInfo().position() == UINT_MAX)
1071         {
1072                 audioFile.metaInfo().setPosition(m_currentFile);
1073         }
1074
1075         return audioFile;
1076 }
1077
1078 void ProcessingDialog::systemTrayActivated(QSystemTrayIcon::ActivationReason reason)
1079 {
1080         if(reason == QSystemTrayIcon::DoubleClick)
1081         {
1082                 lamexp_bring_to_front(this);
1083         }
1084 }
1085
1086 void ProcessingDialog::cpuUsageHasChanged(const double val)
1087 {
1088         
1089         ui->label_cpu->setText(QString().sprintf(" %d%%", qRound(val * 100.0)));
1090         UPDATE_MIN_WIDTH(ui->label_cpu);
1091 }
1092
1093 void ProcessingDialog::ramUsageHasChanged(const double val)
1094 {
1095         
1096         ui->label_ram->setText(QString().sprintf(" %d%%", qRound(val * 100.0)));
1097         UPDATE_MIN_WIDTH(ui->label_ram);
1098 }
1099
1100 void ProcessingDialog::diskUsageHasChanged(const quint64 val)
1101 {
1102         int postfix = 0;
1103         const char *postfixStr[6] = {"B", "KB", "MB", "GB", "TB", "PB"};
1104         double space = static_cast<double>(val);
1105
1106         while((space >= 1000.0) && (postfix < 5))
1107         {
1108                 space = space / 1024.0;
1109                 postfix++;
1110         }
1111
1112         ui->label_disk->setText(QString().sprintf(" %3.1f %s", space, postfixStr[postfix]));
1113         UPDATE_MIN_WIDTH(ui->label_disk);
1114 }
1115
1116 bool ProcessingDialog::shutdownComputer(void)
1117 {
1118         const int iTimeout = m_settings->hibernateComputer() ? 10 : 30;
1119         const Qt::WindowFlags flags = Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowSystemMenuHint;
1120         const QString text = QString("%1%2%1").arg(QString().fill(' ', 18), tr("Warning: Computer will shutdown in %1 seconds..."));
1121         
1122         qWarning("Initiating shutdown sequence!");
1123         
1124         QProgressDialog progressDialog(text.arg(iTimeout), tr("Cancel Shutdown"), 0, iTimeout + 1, this, flags);
1125         QPushButton *cancelButton = new QPushButton(tr("Cancel Shutdown"), &progressDialog);
1126         cancelButton->setIcon(QIcon(":/icons/power_on.png"));
1127         progressDialog.setModal(true);
1128         progressDialog.setAutoClose(false);
1129         progressDialog.setAutoReset(false);
1130         progressDialog.setWindowIcon(QIcon(":/icons/power_off.png"));
1131         progressDialog.setCancelButton(cancelButton);
1132         progressDialog.show();
1133         
1134         qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1135
1136         QApplication::setOverrideCursor(Qt::WaitCursor);
1137         PLAY_SOUND_OPTIONAL("shutdown", false);
1138         QApplication::restoreOverrideCursor();
1139
1140         QTimer timer;
1141         timer.setInterval(1000);
1142         timer.start();
1143
1144         QEventLoop eventLoop(this);
1145         connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
1146         connect(&progressDialog, SIGNAL(canceled()), &eventLoop, SLOT(quit()));
1147
1148         for(int i = 1; i <= iTimeout; i++)
1149         {
1150                 eventLoop.exec();
1151                 if(progressDialog.wasCanceled())
1152                 {
1153                         progressDialog.close();
1154                         return false;
1155                 }
1156                 progressDialog.setValue(i+1);
1157                 progressDialog.setLabelText(text.arg(iTimeout-i));
1158                 if(iTimeout-i == 3) progressDialog.setCancelButton(NULL);
1159                 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1160                 PLAY_SOUND_OPTIONAL(((i < iTimeout) ? "beep" : "beep2"), false);
1161         }
1162         
1163         progressDialog.close();
1164         return true;
1165 }
1166
1167 QString ProcessingDialog::time2text(const double timeVal) const
1168 {
1169         double intPart = 0;
1170         double frcPart = modf(timeVal, &intPart);
1171
1172         QTime time = QTime().addSecs(qRound(intPart)).addMSecs(qRound(frcPart * 1000.0));
1173
1174         QString a, b;
1175
1176         if(time.hour() > 0)
1177         {
1178                 a = tr("%n hour(s)", "", time.hour());
1179                 b = tr("%n minute(s)", "", time.minute());
1180         }
1181         else if(time.minute() > 0)
1182         {
1183                 a = tr("%n minute(s)", "", time.minute());
1184                 b = tr("%n second(s)", "", time.second());
1185         }
1186         else
1187         {
1188                 a = tr("%n second(s)", "", time.second());
1189                 b = tr("%n millisecond(s)", "", time.msec());
1190         }
1191
1192         return QString("%1, %2").arg(a, b);
1193 }
1194
1195 ////////////////////////////////////////////////////////////
1196 // HELPER FUNCTIONS
1197 ////////////////////////////////////////////////////////////
1198
1199 static int cores2instances(int cores)
1200 {
1201         //This function is a "cubic spline" with sampling points at:
1202         //(1,1); (2,2); (4,4); (8,6); (16,8); (32,11); (64,16)
1203         static const double LUT[8][5] =
1204         {
1205                 { 1.0,  0.014353554, -0.043060662, 1.028707108,  0.000000000},
1206                 { 2.0, -0.028707108,  0.215303309, 0.511979167,  0.344485294},
1207                 { 4.0,  0.010016468, -0.249379596, 2.370710784, -2.133823529},
1208                 { 8.0,  0.000282437, -0.015762868, 0.501776961,  2.850000000},
1209                 {16.0,  0.000033270, -0.003802849, 0.310416667,  3.870588235},
1210                 {32.0,  0.000006343, -0.001217831, 0.227696078,  4.752941176},
1211                 {64.0,  0.000000000,  0.000000000, 0.000000000, 16.000000000},
1212                 {DBL_MAX, 0.0, 0.0, 0.0, 0.0}
1213         };
1214
1215         double x = abs(static_cast<double>(cores)), y = 1.0;
1216         
1217         for(size_t i = 0; i < 7; i++)
1218         {
1219                 if((x >= LUT[i][0]) && (x < LUT[i+1][0]))
1220                 {
1221                         y = (((((LUT[i][1] * x) + LUT[i][2]) * x) + LUT[i][3]) * x) + LUT[i][4];
1222                         break;
1223                 }
1224         }
1225
1226         return qRound(y);
1227 }