OSDN Git Service

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