OSDN Git Service

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