OSDN Git Service

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