OSDN Git Service

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