1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2012 LoRd_MuldeR <MuldeR2@GMX.de>
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.
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License along
16 // with this program; if not, write to the Free Software Foundation, Inc.,
17 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
22 #include "Dialog_Processing.h"
25 #include "../tmp/UIC_ProcessingDialog.h"
29 #include "Model_FileList.h"
30 #include "Model_Progress.h"
31 #include "Model_Settings.h"
32 #include "Thread_Process.h"
33 #include "Thread_CPUObserver.h"
34 #include "Thread_RAMObserver.h"
35 #include "Thread_DiskObserver.h"
36 #include "Dialog_LogView.h"
37 #include "Encoder_AAC.h"
38 #include "Encoder_AAC_FHG.h"
39 #include "Encoder_AAC_QAAC.h"
40 #include "Encoder_AC3.h"
41 #include "Encoder_DCA.h"
42 #include "Encoder_FLAC.h"
43 #include "Encoder_MP3.h"
44 #include "Encoder_Vorbis.h"
45 #include "Encoder_Opus.h"
46 #include "Encoder_Wave.h"
47 #include "Registry_Decoder.h"
48 #include "Filter_Downmix.h"
49 #include "Filter_Normalize.h"
50 #include "Filter_Resample.h"
51 #include "Filter_ToneAdjust.h"
52 #include "WinSevenTaskbar.h"
54 #include <QApplication>
56 #include <QDesktopWidget>
58 #include <QMessageBox>
60 #include <QCloseEvent>
61 #include <QDesktopServices>
67 #include <QSystemTrayIcon>
69 #include <QProgressDialog>
70 #include <QResizeEvent>
77 ////////////////////////////////////////////////////////////
79 //Maximum number of parallel instances
80 #define MAX_INSTANCES 16U
82 //Function to calculate the number of instances
83 static int cores2instances(int cores
);
85 ////////////////////////////////////////////////////////////
87 #define CHANGE_BACKGROUND_COLOR(WIDGET, COLOR) do \
89 QPalette palette = WIDGET->palette(); \
90 palette.setColor(QPalette::Background, COLOR); \
91 WIDGET->setPalette(palette); \
95 #define SET_PROGRESS_TEXT(TXT) do \
97 ui->label_progress->setText(TXT); \
98 m_systemTray->setToolTip(QString().sprintf("LameXP v%d.%02d\n%ls", lamexp_version_major(), lamexp_version_minor(), QString(TXT).utf16())); \
102 #define SET_FONT_BOLD(WIDGET,BOLD) do \
104 QFont _font = WIDGET->font(); \
105 _font.setBold(BOLD); WIDGET->setFont(_font); \
109 #define SET_TEXT_COLOR(WIDGET, COLOR) do \
111 QPalette _palette = WIDGET->palette(); \
112 _palette.setColor(QPalette::WindowText, (COLOR)); \
113 _palette.setColor(QPalette::Text, (COLOR)); \
114 WIDGET->setPalette(_palette); \
118 #define UPDATE_MIN_WIDTH(WIDGET) do \
120 if(WIDGET->width() > WIDGET->minimumWidth()) WIDGET->setMinimumWidth(WIDGET->width()); \
124 ////////////////////////////////////////////////////////////
126 //Dummy class for UserData
127 class IntUserData
: public QObjectUserData
130 IntUserData(int value
) : m_value(value
) {/*NOP*/}
131 int value(void) { return m_value
; }
132 void setValue(int value
) { m_value
= value
; }
137 ////////////////////////////////////////////////////////////
139 ////////////////////////////////////////////////////////////
141 ProcessingDialog::ProcessingDialog(FileListModel
*fileListModel
, AudioFileModel
*metaInfo
, SettingsModel
*settings
, QWidget
*parent
)
144 ui(new Ui::ProcessingDialog
),
145 m_systemTray(new QSystemTrayIcon(QIcon(":/icons/cd_go.png"), this)),
146 m_settings(settings
),
147 m_metaInfo(metaInfo
),
148 m_shutdownFlag(shutdownFlag_None
),
149 m_diskObserver(NULL
),
152 m_progressViewFilter(-1),
155 //Init the dialog, from the .ui file
157 setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint
);
160 ui
->label_headerIcon
->setPixmap(lamexp_app_icon().pixmap(ui
->label_headerIcon
->size()));
163 ui
->label_versionInfo
->setText(QString().sprintf("v%d.%02d %s (Build %d)", lamexp_version_major(), lamexp_version_minor(), lamexp_version_release(), lamexp_version_build()));
164 ui
->label_versionInfo
->installEventFilter(this);
167 qRegisterMetaType
<QUuid
>("QUuid");
169 //Center window in screen
170 QRect desktopRect
= QApplication::desktop()->screenGeometry();
171 QRect thisRect
= this->geometry();
172 move((desktopRect
.width() - thisRect
.width()) / 2, (desktopRect
.height() - thisRect
.height()) / 2);
173 setMinimumSize(thisRect
.width(), thisRect
.height());
176 connect(ui
->button_AbortProcess
, SIGNAL(clicked()), this, SLOT(abortEncoding()));
178 //Init progress indicator
179 m_progressIndicator
= new QMovie(":/images/Working.gif");
180 m_progressIndicator
->setCacheMode(QMovie::CacheAll
);
181 m_progressIndicator
->setSpeed(50);
182 ui
->label_headerWorking
->setMovie(m_progressIndicator
);
183 ui
->progressBar
->setValue(0);
185 //Init progress model
186 m_progressModel
= new ProgressModel();
187 ui
->view_log
->setModel(m_progressModel
);
188 ui
->view_log
->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents
);
189 ui
->view_log
->verticalHeader()->hide();
190 ui
->view_log
->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents
);
191 ui
->view_log
->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch
);
192 ui
->view_log
->viewport()->installEventFilter(this);
193 connect(m_progressModel
, SIGNAL(rowsInserted(QModelIndex
,int,int)), this, SLOT(progressModelChanged()));
194 connect(m_progressModel
, SIGNAL(rowsMoved(QModelIndex
,int,int,QModelIndex
,int)), this, SLOT(progressModelChanged()));
195 connect(m_progressModel
, SIGNAL(rowsRemoved(QModelIndex
,int,int)), this, SLOT(progressModelChanged()));
196 connect(m_progressModel
, SIGNAL(modelReset()), this, SLOT(progressModelChanged()));
197 connect(ui
->view_log
, SIGNAL(activated(QModelIndex
)), this, SLOT(logViewDoubleClicked(QModelIndex
)));
198 connect(ui
->view_log
->horizontalHeader(), SIGNAL(sectionResized(int,int,int)), this, SLOT(logViewSectionSizeChanged(int,int,int)));
200 //Create context menu
201 m_contextMenu
= new QMenu();
202 QAction
*contextMenuDetailsAction
= m_contextMenu
->addAction(QIcon(":/icons/zoom.png"), tr("Show details for selected job"));
203 QAction
*contextMenuShowFileAction
= m_contextMenu
->addAction(QIcon(":/icons/folder_go.png"), tr("Browse Output File Location"));
204 m_contextMenu
->addSeparator();
206 //Create "filter" context menu
207 m_progressViewFilterGroup
= new QActionGroup(this);
208 QAction
*contextMenuFilterAction
[5] = {NULL
, NULL
, NULL
, NULL
, NULL
};
209 if(QMenu
*filterMenu
= m_contextMenu
->addMenu(QIcon(":/icons/filter.png"), tr("Filter Log Items")))
211 contextMenuFilterAction
[0] = filterMenu
->addAction(m_progressModel
->getIcon(ProgressModel::JobRunning
), tr("Show Running Only"));
212 contextMenuFilterAction
[1] = filterMenu
->addAction(m_progressModel
->getIcon(ProgressModel::JobComplete
), tr("Show Succeeded Only"));
213 contextMenuFilterAction
[2] = filterMenu
->addAction(m_progressModel
->getIcon(ProgressModel::JobFailed
), tr("Show Failed Only"));
214 contextMenuFilterAction
[3] = filterMenu
->addAction(m_progressModel
->getIcon(ProgressModel::JobSkipped
), tr("Show Skipped Only"));
215 contextMenuFilterAction
[4] = filterMenu
->addAction(m_progressModel
->getIcon(ProgressModel::JobState(-1)), tr("Show All Items"));
216 if(QAction
*act
= contextMenuFilterAction
[0]) { m_progressViewFilterGroup
->addAction(act
); act
->setCheckable(true); act
->setData(ProgressModel::JobRunning
); }
217 if(QAction
*act
= contextMenuFilterAction
[1]) { m_progressViewFilterGroup
->addAction(act
); act
->setCheckable(true); act
->setData(ProgressModel::JobComplete
); }
218 if(QAction
*act
= contextMenuFilterAction
[2]) { m_progressViewFilterGroup
->addAction(act
); act
->setCheckable(true); act
->setData(ProgressModel::JobFailed
); }
219 if(QAction
*act
= contextMenuFilterAction
[3]) { m_progressViewFilterGroup
->addAction(act
); act
->setCheckable(true); act
->setData(ProgressModel::JobSkipped
); }
220 if(QAction
*act
= contextMenuFilterAction
[4]) { m_progressViewFilterGroup
->addAction(act
); act
->setCheckable(true); act
->setData(-1); act
->setChecked(true); }
224 if(m_filterInfoLabel
= new QLabel(ui
->view_log
))
226 m_filterInfoLabel
->setFrameShape(QFrame::NoFrame
);
227 m_filterInfoLabel
->setAlignment(Qt::AlignHCenter
| Qt::AlignVCenter
);
228 m_filterInfoLabel
->setUserData(0, new IntUserData(-1));
229 SET_FONT_BOLD(m_filterInfoLabel
, true);
230 SET_TEXT_COLOR(m_filterInfoLabel
, Qt::darkGray
);
231 m_filterInfoLabel
->setContextMenuPolicy(Qt::CustomContextMenu
);
232 connect(m_filterInfoLabel
, SIGNAL(customContextMenuRequested(QPoint
)), this, SLOT(contextMenuTriggered(QPoint
)));
233 m_filterInfoLabel
->hide();
235 if(m_filterInfoLabelIcon
= new QLabel(ui
->view_log
))
237 m_filterInfoLabelIcon
->setFrameShape(QFrame::NoFrame
);
238 m_filterInfoLabelIcon
->setAlignment(Qt::AlignHCenter
| Qt::AlignTop
);
239 m_filterInfoLabelIcon
->setContextMenuPolicy(Qt::CustomContextMenu
);
240 const QIcon
&ico
= m_progressModel
->getIcon(ProgressModel::JobState(-1));
241 m_filterInfoLabelIcon
->setPixmap(ico
.pixmap(16, 16));
242 connect(m_filterInfoLabelIcon
, SIGNAL(customContextMenuRequested(QPoint
)), this, SLOT(contextMenuTriggered(QPoint
)));
243 m_filterInfoLabelIcon
->hide();
246 //Connect context menu
247 ui
->view_log
->setContextMenuPolicy(Qt::CustomContextMenu
);
248 connect(ui
->view_log
, SIGNAL(customContextMenuRequested(QPoint
)), this, SLOT(contextMenuTriggered(QPoint
)));
249 connect(contextMenuDetailsAction
, SIGNAL(triggered(bool)), this, SLOT(contextMenuDetailsActionTriggered()));
250 connect(contextMenuShowFileAction
, SIGNAL(triggered(bool)), this, SLOT(contextMenuShowFileActionTriggered()));
251 for(size_t i
= 0; i
< 5; i
++)
253 if(contextMenuFilterAction
[i
]) connect(contextMenuFilterAction
[i
], SIGNAL(triggered(bool)), this, SLOT(contextMenuFilterActionTriggered()));
255 SET_FONT_BOLD(contextMenuDetailsAction
, true);
260 for(int i
= 0; i
< fileListModel
->rowCount(); i
++)
262 m_pendingJobs
.append(fileListModel
->getFile(fileListModel
->index(i
,0)));
267 ui
->label_headerStatus
->setText(QString("<b>%1</b><br>%2").arg(tr("Encoding Files"), tr("Your files are being encoded, please be patient...")));
269 //Enable system tray icon
270 connect(m_systemTray
, SIGNAL(activated(QSystemTrayIcon::ActivationReason
)), this, SLOT(systemTrayActivated(QSystemTrayIcon::ActivationReason
)));
273 m_runningThreads
= 0;
276 m_succeededJobs
.clear();
277 m_failedJobs
.clear();
278 m_skippedJobs
.clear();
279 m_userAborted
= false;
280 m_forcedAbort
= false;
284 ////////////////////////////////////////////////////////////
286 ////////////////////////////////////////////////////////////
288 ProcessingDialog::~ProcessingDialog(void)
290 ui
->view_log
->setModel(NULL
);
292 if(m_progressIndicator
)
294 m_progressIndicator
->stop();
299 m_diskObserver
->stop();
300 if(!m_diskObserver
->wait(15000))
302 m_diskObserver
->terminate();
303 m_diskObserver
->wait();
308 m_cpuObserver
->stop();
309 if(!m_cpuObserver
->wait(15000))
311 m_cpuObserver
->terminate();
312 m_cpuObserver
->wait();
317 m_ramObserver
->stop();
318 if(!m_ramObserver
->wait(15000))
320 m_ramObserver
->terminate();
321 m_ramObserver
->wait();
325 while(!m_threadList
.isEmpty())
327 ProcessThread
*thread
= m_threadList
.takeFirst();
333 LAMEXP_DELETE(m_progressIndicator
);
334 LAMEXP_DELETE(m_systemTray
);
335 LAMEXP_DELETE(m_diskObserver
);
336 LAMEXP_DELETE(m_cpuObserver
);
337 LAMEXP_DELETE(m_ramObserver
);
338 LAMEXP_DELETE(m_progressViewFilterGroup
);
339 LAMEXP_DELETE(m_filterInfoLabel
);
340 LAMEXP_DELETE(m_filterInfoLabelIcon
);
341 LAMEXP_DELETE(m_contextMenu
);
342 LAMEXP_DELETE(m_progressModel
);
344 WinSevenTaskbar::setOverlayIcon(this, NULL
);
345 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNoState
);
350 ////////////////////////////////////////////////////////////
352 ////////////////////////////////////////////////////////////
354 void ProcessingDialog::showEvent(QShowEvent
*event
)
356 QDialog::showEvent(event
);
360 static const char *NA
= " N/A";
362 setCloseButtonEnabled(false);
363 ui
->button_closeDialog
->setEnabled(false);
364 ui
->button_AbortProcess
->setEnabled(false);
365 m_systemTray
->setVisible(true);
367 if(!SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS
))
369 SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS
);
372 ui
->label_cpu
->setText(NA
);
373 ui
->label_disk
->setText(NA
);
374 ui
->label_ram
->setText(NA
);
376 QTimer::singleShot(1000, this, SLOT(initEncoding()));
380 //Force update geometry
384 void ProcessingDialog::closeEvent(QCloseEvent
*event
)
386 if(!ui
->button_closeDialog
->isEnabled())
392 m_systemTray
->setVisible(false);
396 bool ProcessingDialog::eventFilter(QObject
*obj
, QEvent
*event
)
398 static QColor defaultColor
= QColor();
400 if(obj
== ui
->label_versionInfo
)
402 if(event
->type() == QEvent::Enter
)
404 QPalette palette
= ui
->label_versionInfo
->palette();
405 defaultColor
= palette
.color(QPalette::Normal
, QPalette::WindowText
);
406 palette
.setColor(QPalette::Normal
, QPalette::WindowText
, Qt::red
);
407 ui
->label_versionInfo
->setPalette(palette
);
409 else if(event
->type() == QEvent::Leave
)
411 QPalette palette
= ui
->label_versionInfo
->palette();
412 palette
.setColor(QPalette::Normal
, QPalette::WindowText
, defaultColor
);
413 ui
->label_versionInfo
->setPalette(palette
);
415 else if(event
->type() == QEvent::MouseButtonPress
)
417 QUrl
url(lamexp_website_url());
418 QDesktopServices::openUrl(url
);
425 bool ProcessingDialog::event(QEvent
*e
)
429 case lamexp_event_queryendsession
:
430 qWarning("System is shutting down, preparing to abort...");
431 if(!m_userAborted
) abortEncoding(true);
433 case lamexp_event_endsession
:
434 qWarning("System is shutting down, encoding will be aborted now...");
439 if(!m_userAborted
) abortEncoding(true);
440 QApplication::processEvents(QEventLoop::WaitForMoreEvents
& QEventLoop::ExcludeUserInputEvents
);
443 m_pendingJobs
.clear();
446 return QDialog::event(e
);
453 void ProcessingDialog::resizeEvent(QResizeEvent
*event
)
455 if(event
) QDialog::resizeEvent(event
);
457 if(QWidget
*port
= ui
->view_log
->viewport())
459 QRect geom
= port
->geometry();
460 m_filterInfoLabel
->setGeometry(geom
.left() + 16, geom
.top() + 16, geom
.width() - 32, 48);
461 m_filterInfoLabelIcon
->setGeometry(geom
.left() + 16, geom
.top() + 64, geom
.width() - 32, geom
.height() - 80);
465 bool ProcessingDialog::winEvent(MSG
*message
, long *result
)
467 return WinSevenTaskbar::handleWinEvent(message
, result
);
470 ////////////////////////////////////////////////////////////
472 ////////////////////////////////////////////////////////////
474 void ProcessingDialog::initEncoding(void)
476 qDebug("Initializing encoding process...");
478 m_runningThreads
= 0;
481 m_succeededJobs
.clear();
482 m_failedJobs
.clear();
483 m_skippedJobs
.clear();
484 m_userAborted
= false;
485 m_forcedAbort
= false;
488 DecoderRegistry::configureDecoders(m_settings
);
490 CHANGE_BACKGROUND_COLOR(ui
->frame_header
, QColor(Qt::white
));
491 SET_PROGRESS_TEXT(tr("Encoding files, please wait..."));
492 m_progressIndicator
->start();
494 ui
->button_closeDialog
->setEnabled(false);
495 ui
->button_AbortProcess
->setEnabled(true);
496 ui
->progressBar
->setRange(0, m_pendingJobs
.count());
497 ui
->checkBox_shutdownComputer
->setEnabled(true);
498 ui
->checkBox_shutdownComputer
->setChecked(false);
500 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState
);
501 WinSevenTaskbar::setTaskbarProgress(this, 0, m_pendingJobs
.count());
502 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/control_play_blue.png"));
506 m_diskObserver
= new DiskObserverThread(m_settings
->customTempPathEnabled() ? m_settings
->customTempPath() : lamexp_temp_folder2());
507 connect(m_diskObserver
, SIGNAL(messageLogged(QString
,int)), m_progressModel
, SLOT(addSystemMessage(QString
,int)), Qt::QueuedConnection
);
508 connect(m_diskObserver
, SIGNAL(freeSpaceChanged(quint64
)), this, SLOT(diskUsageHasChanged(quint64
)), Qt::QueuedConnection
);
509 m_diskObserver
->start();
513 m_cpuObserver
= new CPUObserverThread();
514 connect(m_cpuObserver
, SIGNAL(currentUsageChanged(double)), this, SLOT(cpuUsageHasChanged(double)), Qt::QueuedConnection
);
515 m_cpuObserver
->start();
519 m_ramObserver
= new RAMObserverThread();
520 connect(m_ramObserver
, SIGNAL(currentUsageChanged(double)), this, SLOT(ramUsageHasChanged(double)), Qt::QueuedConnection
);
521 m_ramObserver
->start();
524 unsigned int maximumInstances
= qBound(0U, m_settings
->maximumInstances(), MAX_INSTANCES
);
525 if(maximumInstances
< 1)
527 lamexp_cpu_t cpuFeatures
= lamexp_detect_cpu_features(lamexp_arguments());
528 maximumInstances
= cores2instances(qBound(1, cpuFeatures
.count
, 64));
531 maximumInstances
= qBound(1U, maximumInstances
, static_cast<unsigned int>(m_pendingJobs
.count()));
532 if(maximumInstances
> 1)
534 m_progressModel
->addSystemMessage(tr("Multi-threading enabled: Running %1 instances in parallel!").arg(QString::number(maximumInstances
)));
537 for(unsigned int i
= 0; i
< maximumInstances
; i
++)
540 qApp
->processEvents();
543 LARGE_INTEGER counter
;
544 if(QueryPerformanceCounter(&counter
))
546 m_timerStart
= counter
.QuadPart
;
550 void ProcessingDialog::abortEncoding(bool force
)
552 m_userAborted
= true;
553 if(force
) m_forcedAbort
= true;
554 ui
->button_AbortProcess
->setEnabled(false);
555 SET_PROGRESS_TEXT(tr("Aborted! Waiting for running jobs to terminate..."));
557 for(int i
= 0; i
< m_threadList
.count(); i
++)
559 m_threadList
.at(i
)->abort();
563 void ProcessingDialog::doneEncoding(void)
566 ui
->progressBar
->setValue(ui
->progressBar
->value() + 1);
570 SET_PROGRESS_TEXT(tr("Encoding: %1 files of %2 completed so far, please wait...").arg(QString::number(ui
->progressBar
->value()), QString::number(ui
->progressBar
->maximum())));
571 WinSevenTaskbar::setTaskbarProgress(this, ui
->progressBar
->value(), ui
->progressBar
->maximum());
574 int index
= m_threadList
.indexOf(dynamic_cast<ProcessThread
*>(QWidget::sender()));
577 m_threadList
.takeAt(index
)->deleteLater();
580 if(!m_pendingJobs
.isEmpty() && !m_userAborted
)
583 qDebug("Running jobs: %u", m_runningThreads
);
587 if(m_runningThreads
> 0)
589 qDebug("Running jobs: %u", m_runningThreads
);
593 QApplication::setOverrideCursor(Qt::WaitCursor
);
594 qDebug("Running jobs: %u", m_runningThreads
);
596 if(!m_userAborted
&& m_settings
->createPlaylist() && !m_settings
->outputToSourceDir())
598 SET_PROGRESS_TEXT(tr("Creating the playlist file, please wait..."));
599 QApplication::processEvents();
605 CHANGE_BACKGROUND_COLOR(ui
->frame_header
, QColor("#FFF3BA"));
606 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState
);
607 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/error.png"));
608 SET_PROGRESS_TEXT((m_succeededJobs
.count() > 0) ? tr("Process was aborted by the user after %1 file(s)!").arg(QString::number(m_succeededJobs
.count())) : tr("Process was aborted prematurely by the user!"));
609 m_systemTray
->showMessage(tr("LameXP - Aborted"), tr("Process was aborted by the user."), QSystemTrayIcon::Warning
);
610 m_systemTray
->setIcon(QIcon(":/icons/cd_delete.png"));
611 QApplication::processEvents();
612 if(m_settings
->soundsEnabled() && !m_forcedAbort
)
614 PlaySound(MAKEINTRESOURCE(IDR_WAVE_ABORTED
), GetModuleHandle(NULL
), SND_RESOURCE
| SND_SYNC
);
619 LARGE_INTEGER counter
, frequency
;
620 if(QueryPerformanceCounter(&counter
) && QueryPerformanceFrequency(&frequency
))
622 if((m_timerStart
> 0I64
) && (frequency
.QuadPart
> 0I64
) && (m_timerStart
< counter
.QuadPart
))
624 double timeElapsed
= static_cast<double>(counter
.QuadPart
- m_timerStart
) / static_cast<double>(frequency
.QuadPart
);
625 m_progressModel
->addSystemMessage(tr("Process finished after %1.").arg(time2text(timeElapsed
)), ProgressModel::SysMsg_Performance
);
629 if(m_failedJobs
.count() > 0)
631 CHANGE_BACKGROUND_COLOR(ui
->frame_header
, QColor("#FFBABA"));
632 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState
);
633 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/exclamation.png"));
634 if(m_skippedJobs
.count() > 0)
636 SET_PROGRESS_TEXT(tr("Error: %1 of %2 files failed (%3 files skipped). Double-click failed items for detailed information!").arg(QString::number(m_failedJobs
.count()), QString::number(m_failedJobs
.count() + m_succeededJobs
.count() + m_skippedJobs
.count()), QString::number(m_skippedJobs
.count())));
640 SET_PROGRESS_TEXT(tr("Error: %1 of %2 files failed. Double-click failed items for detailed information!").arg(QString::number(m_failedJobs
.count()), QString::number(m_failedJobs
.count() + m_succeededJobs
.count())));
642 m_systemTray
->showMessage(tr("LameXP - Error"), tr("At least one file has failed!"), QSystemTrayIcon::Critical
);
643 m_systemTray
->setIcon(QIcon(":/icons/cd_delete.png"));
644 QApplication::processEvents();
645 if(m_settings
->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR
), GetModuleHandle(NULL
), SND_RESOURCE
| SND_SYNC
);
649 CHANGE_BACKGROUND_COLOR(ui
->frame_header
, QColor("#E0FFE2"));
650 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState
);
651 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/accept.png"));
652 if(m_skippedJobs
.count() > 0)
654 SET_PROGRESS_TEXT(tr("All files completed successfully. Skipped %1 files.").arg(QString::number(m_skippedJobs
.count())));
658 SET_PROGRESS_TEXT(tr("All files completed successfully."));
660 m_systemTray
->showMessage(tr("LameXP - Done"), tr("All files completed successfully."), QSystemTrayIcon::Information
);
661 m_systemTray
->setIcon(QIcon(":/icons/cd_add.png"));
662 QApplication::processEvents();
663 if(m_settings
->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_SUCCESS
), GetModuleHandle(NULL
), SND_RESOURCE
| SND_SYNC
);
667 setCloseButtonEnabled(true);
668 ui
->button_closeDialog
->setEnabled(true);
669 ui
->button_AbortProcess
->setEnabled(false);
670 ui
->checkBox_shutdownComputer
->setEnabled(false);
672 m_progressModel
->restoreHiddenItems();
673 ui
->view_log
->scrollToBottom();
674 m_progressIndicator
->stop();
675 ui
->progressBar
->setValue(ui
->progressBar
->maximum());
676 WinSevenTaskbar::setTaskbarProgress(this, ui
->progressBar
->value(), ui
->progressBar
->maximum());
678 QApplication::restoreOverrideCursor();
680 if(!m_userAborted
&& ui
->checkBox_shutdownComputer
->isChecked())
682 if(shutdownComputer())
684 m_shutdownFlag
= m_settings
->hibernateComputer() ? shutdownFlag_Hibernate
: shutdownFlag_TurnPowerOff
;
690 void ProcessingDialog::processFinished(const QUuid
&jobId
, const QString
&outFileName
, int success
)
694 m_playList
.insert(jobId
, outFileName
);
695 m_succeededJobs
.append(jobId
);
699 m_playList
.insert(jobId
, outFileName
);
700 m_skippedJobs
.append(jobId
);
704 m_failedJobs
.append(jobId
);
707 //Update filter as soon as a job finished!
708 if(m_progressViewFilter
>= 0)
710 QTimer::singleShot(0, this, SLOT(progressViewFilterChanged()));
714 void ProcessingDialog::progressModelChanged(void)
716 //Update filter as soon as the model changes!
717 if(m_progressViewFilter
>= 0)
719 QTimer::singleShot(0, this, SLOT(progressViewFilterChanged()));
722 QTimer::singleShot(0, ui
->view_log
, SLOT(scrollToBottom()));
725 void ProcessingDialog::logViewDoubleClicked(const QModelIndex
&index
)
727 if(m_runningThreads
== 0)
729 const QStringList
&logFile
= m_progressModel
->getLogFile(index
);
731 if(!logFile
.isEmpty())
733 LogViewDialog
*logView
= new LogViewDialog(this);
734 logView
->setWindowTitle(QString("LameXP - [%1]").arg(m_progressModel
->data(index
, Qt::DisplayRole
).toString()));
735 logView
->exec(logFile
);
736 LAMEXP_DELETE(logView
);
740 QMessageBox::information(this, windowTitle(), m_progressModel
->data(m_progressModel
->index(index
.row(), 0)).toString());
745 MessageBeep(MB_ICONWARNING
);
749 void ProcessingDialog::logViewSectionSizeChanged(int logicalIndex
, int oldSize
, int newSize
)
751 if(logicalIndex
== 1)
753 if(QHeaderView
*hdr
= ui
->view_log
->horizontalHeader())
755 hdr
->setMinimumSectionSize(qMax(hdr
->minimumSectionSize(), hdr
->sectionSize(1)));
760 void ProcessingDialog::contextMenuTriggered(const QPoint
&pos
)
762 QAbstractScrollArea
*scrollArea
= dynamic_cast<QAbstractScrollArea
*>(QObject::sender());
763 QWidget
*sender
= scrollArea
? scrollArea
->viewport() : dynamic_cast<QWidget
*>(QObject::sender());
765 if(pos
.x() <= sender
->width() && pos
.y() <= sender
->height() && pos
.x() >= 0 && pos
.y() >= 0)
767 m_contextMenu
->popup(sender
->mapToGlobal(pos
));
771 void ProcessingDialog::contextMenuDetailsActionTriggered(void)
773 QModelIndex index
= ui
->view_log
->indexAt(ui
->view_log
->viewport()->mapFromGlobal(m_contextMenu
->pos()));
774 logViewDoubleClicked(index
.isValid() ? index
: ui
->view_log
->currentIndex());
777 void ProcessingDialog::contextMenuShowFileActionTriggered(void)
779 QModelIndex index
= ui
->view_log
->indexAt(ui
->view_log
->viewport()->mapFromGlobal(m_contextMenu
->pos()));
780 const QUuid
&jobId
= m_progressModel
->getJobId(index
.isValid() ? index
: ui
->view_log
->currentIndex());
781 QString filePath
= m_playList
.value(jobId
, QString());
783 if(filePath
.isEmpty())
785 MessageBeep(MB_ICONWARNING
);
789 if(QFileInfo(filePath
).exists())
791 QString systemRootPath
;
793 QDir
systemRoot(lamexp_known_folder(lamexp_folder_systemfolder
));
794 if(systemRoot
.exists() && systemRoot
.cdUp())
796 systemRootPath
= systemRoot
.canonicalPath();
799 if(!systemRootPath
.isEmpty())
801 QFileInfo
explorer(QString("%1/explorer.exe").arg(systemRootPath
));
802 if(explorer
.exists() && explorer
.isFile())
804 QProcess::execute(explorer
.canonicalFilePath(), QStringList() << "/select," << QDir::toNativeSeparators(QFileInfo(filePath
).canonicalFilePath()));
810 qWarning("SystemRoot directory could not be detected!");
815 qWarning("File not found: %s", filePath
.toLatin1().constData());
816 MessageBeep(MB_ICONERROR
);
820 void ProcessingDialog::contextMenuFilterActionTriggered(void)
822 if(QAction
*action
= dynamic_cast<QAction
*>(QObject::sender()))
824 if(action
->data().type() == QVariant::Int
)
826 m_progressViewFilter
= action
->data().toInt();
827 progressViewFilterChanged();
828 QTimer::singleShot(0, this, SLOT(progressViewFilterChanged()));
829 QTimer::singleShot(0, ui
->view_log
, SLOT(scrollToBottom()));
830 action
->setChecked(true);
836 * Filter progress items
838 void ProcessingDialog::progressViewFilterChanged(void)
840 bool matchFound
= false;
842 for(int i
= 0; i
< ui
->view_log
->model()->rowCount(); i
++)
844 QModelIndex index
= (m_progressViewFilter
>= 0) ? m_progressModel
->index(i
, 0) : QModelIndex();
845 const bool bHide
= index
.isValid() ? (m_progressModel
->getJobState(index
) != m_progressViewFilter
) : false;
846 ui
->view_log
->setRowHidden(i
, bHide
); matchFound
= matchFound
|| (!bHide
);
849 if((m_progressViewFilter
>= 0) && (!matchFound
))
851 if(m_filterInfoLabel
->isHidden() || (dynamic_cast<IntUserData
*>(m_filterInfoLabel
->userData(0))->value() != m_progressViewFilter
))
853 dynamic_cast<IntUserData
*>(m_filterInfoLabel
->userData(0))->setValue(m_progressViewFilter
);
854 m_filterInfoLabel
->setText(QString("<p>» %1 «</p>").arg(tr("None of the items matches the current filtering rules")));
855 m_filterInfoLabel
->show();
856 m_filterInfoLabelIcon
->setPixmap(m_progressModel
->getIcon(static_cast<ProgressModel::JobState
>(m_progressViewFilter
)).pixmap(16, 16, QIcon::Disabled
));
857 m_filterInfoLabelIcon
->show();
861 else if(!m_filterInfoLabel
->isHidden())
863 m_filterInfoLabel
->hide();
864 m_filterInfoLabelIcon
->hide();
868 ////////////////////////////////////////////////////////////
870 ////////////////////////////////////////////////////////////
872 void ProcessingDialog::startNextJob(void)
874 if(m_pendingJobs
.isEmpty())
880 AudioFileModel currentFile
= updateMetaInfo(m_pendingJobs
.takeFirst());
881 bool nativeResampling
= false;
883 //Create encoder instance
884 AbstractEncoder
*encoder
= makeEncoder(&nativeResampling
);
886 //Create processing thread
887 ProcessThread
*thread
= new ProcessThread
890 (m_settings
->outputToSourceDir() ? QFileInfo(currentFile
.filePath()).absolutePath() : m_settings
->outputDir()),
891 (m_settings
->customTempPathEnabled() ? m_settings
->customTempPath() : lamexp_temp_folder2()),
893 m_settings
->prependRelativeSourcePath() && (!m_settings
->outputToSourceDir())
897 if(m_settings
->forceStereoDownmix())
899 thread
->addFilter(new DownmixFilter());
901 if((m_settings
->samplingRate() > 0) && !nativeResampling
)
903 if(SettingsModel::samplingRates
[m_settings
->samplingRate()] != currentFile
.formatAudioSamplerate() || currentFile
.formatAudioSamplerate() == 0)
905 thread
->addFilter(new ResampleFilter(SettingsModel::samplingRates
[m_settings
->samplingRate()]));
908 if((m_settings
->toneAdjustBass() != 0) || (m_settings
->toneAdjustTreble() != 0))
910 thread
->addFilter(new ToneAdjustFilter(m_settings
->toneAdjustBass(), m_settings
->toneAdjustTreble()));
912 if(m_settings
->normalizationFilterEnabled())
914 thread
->addFilter(new NormalizeFilter(m_settings
->normalizationFilterMaxVolume(), m_settings
->normalizationFilterEqualizationMode()));
916 if(m_settings
->renameOutputFilesEnabled() && (!m_settings
->renameOutputFilesPattern().simplified().isEmpty()))
918 thread
->setRenamePattern(m_settings
->renameOutputFilesPattern());
920 if(m_settings
->overwriteMode() != SettingsModel::Overwrite_KeepBoth
)
922 thread
->setOverwriteMode((m_settings
->overwriteMode() == SettingsModel::Overwrite_SkipFile
), (m_settings
->overwriteMode() == SettingsModel::Overwrite_Replaces
));
925 m_threadList
.append(thread
);
926 m_allJobs
.append(thread
->getId());
928 //Connect thread signals
929 connect(thread
, SIGNAL(finished()), this, SLOT(doneEncoding()), Qt::QueuedConnection
);
930 connect(thread
, SIGNAL(processStateInitialized(QUuid
,QString
,QString
,int)), m_progressModel
, SLOT(addJob(QUuid
,QString
,QString
,int)), Qt::QueuedConnection
);
931 connect(thread
, SIGNAL(processStateChanged(QUuid
,QString
,int)), m_progressModel
, SLOT(updateJob(QUuid
,QString
,int)), Qt::QueuedConnection
);
932 connect(thread
, SIGNAL(processStateFinished(QUuid
,QString
,int)), this, SLOT(processFinished(QUuid
,QString
,int)), Qt::QueuedConnection
);
933 connect(thread
, SIGNAL(processMessageLogged(QUuid
,QString
)), m_progressModel
, SLOT(appendToLog(QUuid
,QString
)), Qt::QueuedConnection
);
939 //Give thread some advance
940 for(unsigned int i
= 0; i
< MAX_INSTANCES
; i
++)
942 QThread::yieldCurrentThread();
946 AbstractEncoder
*ProcessingDialog::makeEncoder(bool *nativeResampling
)
948 AbstractEncoder
*encoder
= NULL
;
949 *nativeResampling
= false;
951 switch(m_settings
->compressionEncoder())
953 case SettingsModel::MP3Encoder
:
955 MP3Encoder
*mp3Encoder
= new MP3Encoder();
956 mp3Encoder
->setBitrate(m_settings
->compressionBitrate());
957 mp3Encoder
->setRCMode(m_settings
->compressionRCMode());
958 mp3Encoder
->setAlgoQuality(m_settings
->lameAlgoQuality());
959 if(m_settings
->bitrateManagementEnabled())
961 mp3Encoder
->setBitrateLimits(m_settings
->bitrateManagementMinRate(), m_settings
->bitrateManagementMaxRate());
963 if(m_settings
->samplingRate() > 0)
965 mp3Encoder
->setSamplingRate(SettingsModel::samplingRates
[m_settings
->samplingRate()]);
966 *nativeResampling
= true;
968 mp3Encoder
->setChannelMode(m_settings
->lameChannelMode());
969 mp3Encoder
->setCustomParams(m_settings
->customParametersLAME());
970 encoder
= mp3Encoder
;
973 case SettingsModel::VorbisEncoder
:
975 VorbisEncoder
*vorbisEncoder
= new VorbisEncoder();
976 vorbisEncoder
->setBitrate(m_settings
->compressionBitrate());
977 vorbisEncoder
->setRCMode(m_settings
->compressionRCMode());
978 if(m_settings
->bitrateManagementEnabled())
980 vorbisEncoder
->setBitrateLimits(m_settings
->bitrateManagementMinRate(), m_settings
->bitrateManagementMaxRate());
982 if(m_settings
->samplingRate() > 0)
984 vorbisEncoder
->setSamplingRate(SettingsModel::samplingRates
[m_settings
->samplingRate()]);
985 *nativeResampling
= true;
987 vorbisEncoder
->setCustomParams(m_settings
->customParametersOggEnc());
988 encoder
= vorbisEncoder
;
991 case SettingsModel::AACEncoder
:
993 if(lamexp_check_tool("qaac.exe") && lamexp_check_tool("libsoxrate.dll"))
995 QAACEncoder
*aacEncoder
= new QAACEncoder();
996 aacEncoder
->setBitrate(m_settings
->compressionBitrate());
997 aacEncoder
->setRCMode(m_settings
->compressionRCMode());
998 aacEncoder
->setProfile(m_settings
->aacEncProfile());
999 aacEncoder
->setCustomParams(m_settings
->customParametersAacEnc());
1000 encoder
= aacEncoder
;
1002 else if(lamexp_check_tool("fhgaacenc.exe") && lamexp_check_tool("enc_fhgaac.dll"))
1004 FHGAACEncoder
*aacEncoder
= new FHGAACEncoder();
1005 aacEncoder
->setBitrate(m_settings
->compressionBitrate());
1006 aacEncoder
->setRCMode(m_settings
->compressionRCMode());
1007 aacEncoder
->setProfile(m_settings
->aacEncProfile());
1008 aacEncoder
->setCustomParams(m_settings
->customParametersAacEnc());
1009 encoder
= aacEncoder
;
1013 AACEncoder
*aacEncoder
= new AACEncoder();
1014 aacEncoder
->setBitrate(m_settings
->compressionBitrate());
1015 aacEncoder
->setRCMode(m_settings
->compressionRCMode());
1016 aacEncoder
->setEnable2Pass(m_settings
->neroAACEnable2Pass());
1017 aacEncoder
->setProfile(m_settings
->aacEncProfile());
1018 aacEncoder
->setCustomParams(m_settings
->customParametersAacEnc());
1019 encoder
= aacEncoder
;
1023 case SettingsModel::AC3Encoder
:
1025 AC3Encoder
*ac3Encoder
= new AC3Encoder();
1026 ac3Encoder
->setBitrate(m_settings
->compressionBitrate());
1027 ac3Encoder
->setRCMode(m_settings
->compressionRCMode());
1028 ac3Encoder
->setCustomParams(m_settings
->customParametersAften());
1029 ac3Encoder
->setAudioCodingMode(m_settings
->aftenAudioCodingMode());
1030 ac3Encoder
->setDynamicRangeCompression(m_settings
->aftenDynamicRangeCompression());
1031 ac3Encoder
->setExponentSearchSize(m_settings
->aftenExponentSearchSize());
1032 ac3Encoder
->setFastBitAllocation(m_settings
->aftenFastBitAllocation());
1033 encoder
= ac3Encoder
;
1036 case SettingsModel::FLACEncoder
:
1038 FLACEncoder
*flacEncoder
= new FLACEncoder();
1039 flacEncoder
->setBitrate(m_settings
->compressionBitrate());
1040 flacEncoder
->setRCMode(m_settings
->compressionRCMode());
1041 flacEncoder
->setCustomParams(m_settings
->customParametersFLAC());
1042 encoder
= flacEncoder
;
1045 case SettingsModel::OpusEncoder
:
1047 OpusEncoder
*opusEncoder
= new OpusEncoder();
1048 opusEncoder
->setBitrate(m_settings
->compressionBitrate());
1049 opusEncoder
->setRCMode(m_settings
->compressionRCMode());
1050 opusEncoder
->setOptimizeFor(m_settings
->opusOptimizeFor());
1051 opusEncoder
->setEncodeComplexity(m_settings
->opusComplexity());
1052 opusEncoder
->setFrameSize(m_settings
->opusFramesize());
1053 opusEncoder
->setCustomParams(m_settings
->customParametersOpus());
1054 encoder
= opusEncoder
;
1056 break; case SettingsModel::DCAEncoder
:
1058 DCAEncoder
*dcaEncoder
= new DCAEncoder();
1059 dcaEncoder
->setBitrate(m_settings
->compressionBitrate());
1060 dcaEncoder
->setRCMode(m_settings
->compressionRCMode());
1061 encoder
= dcaEncoder
;
1064 case SettingsModel::PCMEncoder
:
1066 WaveEncoder
*waveEncoder
= new WaveEncoder();
1067 waveEncoder
->setBitrate(m_settings
->compressionBitrate());
1068 waveEncoder
->setRCMode(m_settings
->compressionRCMode());
1069 encoder
= waveEncoder
;
1073 throw "Unsupported encoder!";
1079 void ProcessingDialog::writePlayList(void)
1081 if(m_succeededJobs
.count() <= 0 || m_allJobs
.count() <= 0)
1083 qWarning("WritePlayList: Nothing to do!");
1087 //Init local variables
1089 QRegExp
regExp1("\\[\\d\\d\\][^/\\\\]+$", Qt::CaseInsensitive
);
1090 QRegExp
regExp2("\\(\\d\\d\\)[^/\\\\]+$", Qt::CaseInsensitive
);
1091 QRegExp
regExp3("\\d\\d[^/\\\\]+$", Qt::CaseInsensitive
);
1092 bool usePrefix
[3] = {true, true, true};
1093 bool useUtf8
= false;
1096 //Generate playlist name
1097 QString playListName
= (m_metaInfo
->fileAlbum().isEmpty() ? "Playlist" : m_metaInfo
->fileAlbum());
1098 if(!m_metaInfo
->fileArtist().isEmpty())
1100 playListName
= QString("%1 - %2").arg(m_metaInfo
->fileArtist(), playListName
);
1103 //Clean playlist name
1104 playListName
= lamexp_clean_filename(playListName
);
1106 //Create list of audio files
1107 for(int i
= 0; i
< m_allJobs
.count(); i
++)
1109 if(!m_succeededJobs
.contains(m_allJobs
.at(i
))) continue;
1110 list
<< QDir::toNativeSeparators(QDir(m_settings
->outputDir()).relativeFilePath(m_playList
.value(m_allJobs
.at(i
), "N/A")));
1114 for(int i
= 0; i
< list
.count(); i
++)
1116 if(regExp1
.indexIn(list
.at(i
)) < 0) usePrefix
[0] = false;
1117 if(regExp2
.indexIn(list
.at(i
)) < 0) usePrefix
[1] = false;
1118 if(regExp3
.indexIn(list
.at(i
)) < 0) usePrefix
[2] = false;
1120 if(usePrefix
[0] || usePrefix
[1] || usePrefix
[2])
1122 playListName
.prepend(usePrefix
[0] ? "[00] " : (usePrefix
[1] ? "(00) " : "00 "));
1125 //Do we need an UTF-8 playlist?
1126 for(int i
= 0; i
< list
.count(); i
++)
1128 if(wcscmp(QWCHAR(QString::fromLatin1(list
.at(i
).toLatin1().constData())), QWCHAR(list
.at(i
))))
1135 //Generate playlist output file
1136 QString playListFile
= QString("%1/%2.%3").arg(m_settings
->outputDir(), playListName
, (useUtf8
? "m3u8" : "m3u"));
1137 while(QFileInfo(playListFile
).exists())
1139 playListFile
= QString("%1/%2 (%3).%4").arg(m_settings
->outputDir(), playListName
, QString::number(++counter
), (useUtf8
? "m3u8" : "m3u"));
1142 //Now write playlist to output file
1143 QFile
playList(playListFile
);
1144 if(playList
.open(QIODevice::WriteOnly
))
1148 playList
.write("\xef\xbb\xbf");
1150 playList
.write("#EXTM3U\r\n");
1151 while(!list
.isEmpty())
1153 playList
.write(useUtf8
? list
.takeFirst().toUtf8().constData() : list
.takeFirst().toLatin1().constData());
1154 playList
.write("\r\n");
1160 QMessageBox::warning(this, tr("Playlist creation failed"), QString("%1<br><nobr>%2</nobr>").arg(tr("The playlist file could not be created:"), playListFile
));
1164 AudioFileModel
ProcessingDialog::updateMetaInfo(const AudioFileModel
&audioFile
)
1166 if(!m_settings
->writeMetaTags())
1168 return AudioFileModel(audioFile
, false);
1171 AudioFileModel result
= audioFile
;
1172 result
.updateMetaInfo(*m_metaInfo
);
1174 if(m_metaInfo
->filePosition() == UINT_MAX
)
1176 result
.setFilePosition(m_currentFile
);
1182 void ProcessingDialog::setCloseButtonEnabled(bool enabled
)
1184 HMENU hMenu
= GetSystemMenu((HWND
) winId(), FALSE
);
1185 EnableMenuItem(hMenu
, SC_CLOSE
, MF_BYCOMMAND
| (enabled
? MF_ENABLED
: MF_GRAYED
));
1188 void ProcessingDialog::systemTrayActivated(QSystemTrayIcon::ActivationReason reason
)
1190 if(reason
== QSystemTrayIcon::DoubleClick
)
1192 SetForegroundWindow(reinterpret_cast<HWND
>(this->winId()));
1196 void ProcessingDialog::cpuUsageHasChanged(const double val
)
1199 ui
->label_cpu
->setText(QString().sprintf(" %d%%", qRound(val
* 100.0)));
1200 UPDATE_MIN_WIDTH(ui
->label_cpu
);
1203 void ProcessingDialog::ramUsageHasChanged(const double val
)
1206 ui
->label_ram
->setText(QString().sprintf(" %d%%", qRound(val
* 100.0)));
1207 UPDATE_MIN_WIDTH(ui
->label_ram
);
1210 void ProcessingDialog::diskUsageHasChanged(const quint64 val
)
1213 const char *postfixStr
[6] = {"B", "KB", "MB", "GB", "TB", "PB"};
1214 double space
= static_cast<double>(val
);
1216 while((space
>= 1000.0) && (postfix
< 5))
1218 space
= space
/ 1024.0;
1222 ui
->label_disk
->setText(QString().sprintf(" %3.1f %s", space
, postfixStr
[postfix
]));
1223 UPDATE_MIN_WIDTH(ui
->label_disk
);
1226 bool ProcessingDialog::shutdownComputer(void)
1228 const int iTimeout
= m_settings
->hibernateComputer() ? 10 : 30;
1229 const Qt::WindowFlags flags
= Qt::WindowStaysOnTopHint
| Qt::CustomizeWindowHint
| Qt::WindowTitleHint
| Qt::MSWindowsFixedSizeDialogHint
| Qt::WindowSystemMenuHint
;
1230 const QString text
= QString("%1%2%1").arg(QString().fill(' ', 18), tr("Warning: Computer will shutdown in %1 seconds..."));
1232 qWarning("Initiating shutdown sequence!");
1234 QProgressDialog
progressDialog(text
.arg(iTimeout
), tr("Cancel Shutdown"), 0, iTimeout
+ 1, this, flags
);
1235 QPushButton
*cancelButton
= new QPushButton(tr("Cancel Shutdown"), &progressDialog
);
1236 cancelButton
->setIcon(QIcon(":/icons/power_on.png"));
1237 progressDialog
.setModal(true);
1238 progressDialog
.setAutoClose(false);
1239 progressDialog
.setAutoReset(false);
1240 progressDialog
.setWindowIcon(QIcon(":/icons/power_off.png"));
1241 progressDialog
.setCancelButton(cancelButton
);
1242 progressDialog
.show();
1244 QApplication::processEvents();
1246 if(m_settings
->soundsEnabled())
1248 QApplication::setOverrideCursor(Qt::WaitCursor
);
1249 PlaySound(MAKEINTRESOURCE(IDR_WAVE_SHUTDOWN
), GetModuleHandle(NULL
), SND_RESOURCE
| SND_SYNC
);
1250 QApplication::restoreOverrideCursor();
1254 timer
.setInterval(1000);
1257 QEventLoop
eventLoop(this);
1258 connect(&timer
, SIGNAL(timeout()), &eventLoop
, SLOT(quit()));
1259 connect(&progressDialog
, SIGNAL(canceled()), &eventLoop
, SLOT(quit()));
1261 for(int i
= 1; i
<= iTimeout
; i
++)
1264 if(progressDialog
.wasCanceled())
1266 progressDialog
.close();
1269 progressDialog
.setValue(i
+1);
1270 progressDialog
.setLabelText(text
.arg(iTimeout
-i
));
1271 if(iTimeout
-i
== 3) progressDialog
.setCancelButton(NULL
);
1272 QApplication::processEvents();
1273 PlaySound(MAKEINTRESOURCE((i
< iTimeout
) ? IDR_WAVE_BEEP
: IDR_WAVE_BEEP_LONG
), GetModuleHandle(NULL
), SND_RESOURCE
| SND_SYNC
);
1276 progressDialog
.close();
1280 QString
ProcessingDialog::time2text(const double timeVal
) const
1283 double frcPart
= modf(timeVal
, &intPart
);
1284 int x
= 0, y
= 0; QString a
, b
;
1286 QTime time
= QTime().addSecs(qRound(intPart
)).addMSecs(qRound(frcPart
* 1000.0));
1290 x
= time
.hour(); a
= tr("hour(s)");
1291 y
= time
.minute(); b
= tr("minute(s)");
1293 else if(time
.minute() > 0)
1295 x
= time
.minute(); a
= tr("minute(s)");
1296 y
= time
.second(); b
= tr("second(s)");
1300 x
= time
.second(); a
= tr("second(s)");
1301 y
= time
.msec(); b
= tr("millisecond(s)");
1304 return QString("%1 %2, %3 %4").arg(QString::number(x
), a
, QString::number(y
), b
);
1307 ////////////////////////////////////////////////////////////
1309 ////////////////////////////////////////////////////////////
1311 static int cores2instances(int cores
)
1313 //This function is a "cubic spline" with sampling points at:
1314 //(1,1); (2,2); (4,4); (8,6); (16,8); (32,11); (64,16)
1315 static const double LUT
[8][5] =
1317 { 1.0, 0.014353554, -0.043060662, 1.028707108, 0.000000000},
1318 { 2.0, -0.028707108, 0.215303309, 0.511979167, 0.344485294},
1319 { 4.0, 0.010016468, -0.249379596, 2.370710784, -2.133823529},
1320 { 8.0, 0.000282437, -0.015762868, 0.501776961, 2.850000000},
1321 {16.0, 0.000033270, -0.003802849, 0.310416667, 3.870588235},
1322 {32.0, 0.000006343, -0.001217831, 0.227696078, 4.752941176},
1323 {64.0, 0.000000000, 0.000000000, 0.000000000, 16.000000000},
1324 {DBL_MAX
, 0.0, 0.0, 0.0, 0.0}
1327 double x
= abs(static_cast<double>(cores
)), y
= 1.0;
1329 for(size_t i
= 0; i
< 7; i
++)
1331 if((x
>= LUT
[i
][0]) && (x
< LUT
[i
+1][0]))
1333 y
= (((((LUT
[i
][1] * x
) + LUT
[i
][2]) * x
) + LUT
[i
][3]) * x
) + LUT
[i
][4];