OSDN Git Service

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