OSDN Git Service

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