OSDN Git Service

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