1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2014 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, but always including the *additional*
9 // restrictions defined in the "License.txt" file.
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.
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.
20 // http://www.gnu.org/licenses/gpl-2.0.txt
21 ///////////////////////////////////////////////////////////////////////////////
23 #include "Dialog_Processing.h"
26 #include "UIC_ProcessingDialog.h"
30 #include "Model_FileList.h"
31 #include "Model_Progress.h"
32 #include "Model_Settings.h"
33 #include "Thread_Process.h"
34 #include "Thread_CPUObserver.h"
35 #include "Thread_RAMObserver.h"
36 #include "Thread_DiskObserver.h"
37 #include "Dialog_LogView.h"
38 #include "Registry_Decoder.h"
39 #include "Registry_Encoder.h"
40 #include "Filter_Downmix.h"
41 #include "Filter_Normalize.h"
42 #include "Filter_Resample.h"
43 #include "Filter_ToneAdjust.h"
44 #include "WinSevenTaskbar.h"
47 #include <MUtils/Global.h>
50 #include <QApplication>
52 #include <QDesktopWidget>
54 #include <QMessageBox>
56 #include <QCloseEvent>
57 #include <QDesktopServices>
63 #include <QSystemTrayIcon>
65 #include <QProgressDialog>
66 #include <QResizeEvent>
68 #include <QThreadPool>
73 ////////////////////////////////////////////////////////////
75 //Maximum number of parallel instances
76 #define MAX_INSTANCES 16U
78 //Function to calculate the number of instances
79 static int cores2instances(int cores);
81 ////////////////////////////////////////////////////////////
83 #define CHANGE_BACKGROUND_COLOR(WIDGET, COLOR) do \
85 QPalette palette = WIDGET->palette(); \
86 palette.setColor(QPalette::Background, COLOR); \
87 WIDGET->setPalette(palette); \
91 #define SET_PROGRESS_TEXT(TXT) do \
93 ui->label_progress->setText(TXT); \
94 m_systemTray->setToolTip(QString().sprintf("LameXP v%d.%02d\n%ls", lamexp_version_major(), lamexp_version_minor(), QString(TXT).utf16())); \
98 #define SET_FONT_BOLD(WIDGET,BOLD) do \
100 QFont _font = WIDGET->font(); \
101 _font.setBold(BOLD); WIDGET->setFont(_font); \
105 #define SET_TEXT_COLOR(WIDGET, COLOR) do \
107 QPalette _palette = WIDGET->palette(); \
108 _palette.setColor(QPalette::WindowText, (COLOR)); \
109 _palette.setColor(QPalette::Text, (COLOR)); \
110 WIDGET->setPalette(_palette); \
114 #define UPDATE_MIN_WIDTH(WIDGET) do \
116 if(WIDGET->width() > WIDGET->minimumWidth()) WIDGET->setMinimumWidth(WIDGET->width()); \
120 #define PLAY_SOUND_OPTIONAL(NAME, ASYNC) do \
122 if(m_settings->soundsEnabled()) lamexp_play_sound((NAME), (ASYNC)); \
126 #define IS_VBR(RC_MODE) ((RC_MODE) == SettingsModel::VBRMode)
128 ////////////////////////////////////////////////////////////
130 //Dummy class for UserData
131 class IntUserData : public QObjectUserData
134 IntUserData(int value) : m_value(value) {/*NOP*/}
135 int value(void) { return m_value; }
136 void setValue(int value) { m_value = value; }
141 ////////////////////////////////////////////////////////////
143 ////////////////////////////////////////////////////////////
145 ProcessingDialog::ProcessingDialog(FileListModel *fileListModel, const AudioFileModel_MetaInfo *metaInfo, SettingsModel *settings, QWidget *parent)
148 ui(new Ui::ProcessingDialog),
150 m_systemTray(new QSystemTrayIcon(QIcon(":/icons/cd_go.png"), this)),
151 m_settings(settings),
152 m_metaInfo(metaInfo),
153 m_shutdownFlag(shutdownFlag_None),
155 m_diskObserver(NULL),
158 m_progressViewFilter(-1),
160 m_defaultColor(new QColor()),
163 //Init the dialog, from the .ui file
165 setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint);
167 //Update the window icon
168 m_windowIcon = lamexp_set_window_icon(this, lamexp_app_icon(), true);
171 ui->label_headerIcon->setPixmap(lamexp_app_icon().pixmap(ui->label_headerIcon->size()));
174 ui->label_versionInfo->setText(QString().sprintf("v%d.%02d %s (Build %d)", lamexp_version_major(), lamexp_version_minor(), lamexp_version_release(), lamexp_version_build()));
175 ui->label_versionInfo->installEventFilter(this);
178 qRegisterMetaType<QUuid>("QUuid");
180 //Center window in screen
181 QRect desktopRect = QApplication::desktop()->screenGeometry();
182 QRect thisRect = this->geometry();
183 move((desktopRect.width() - thisRect.width()) / 2, (desktopRect.height() - thisRect.height()) / 2);
184 setMinimumSize(thisRect.width(), thisRect.height());
187 connect(ui->button_AbortProcess, SIGNAL(clicked()), this, SLOT(abortEncoding()));
189 //Init progress indicator
190 m_progressIndicator = new QMovie(":/images/Working.gif");
191 m_progressIndicator->setCacheMode(QMovie::CacheAll);
192 ui->label_headerWorking->setMovie(m_progressIndicator);
193 ui->progressBar->setValue(0);
195 //Init progress model
196 m_progressModel = new ProgressModel();
197 ui->view_log->setModel(m_progressModel);
198 ui->view_log->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
199 ui->view_log->verticalHeader()->hide();
200 ui->view_log->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);
201 ui->view_log->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
202 ui->view_log->viewport()->installEventFilter(this);
203 connect(m_progressModel, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(progressModelChanged()));
204 connect(m_progressModel, SIGNAL(rowsMoved(QModelIndex,int,int,QModelIndex,int)), this, SLOT(progressModelChanged()));
205 connect(m_progressModel, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(progressModelChanged()));
206 connect(m_progressModel, SIGNAL(modelReset()), this, SLOT(progressModelChanged()));
207 connect(ui->view_log, SIGNAL(activated(QModelIndex)), this, SLOT(logViewDoubleClicked(QModelIndex)));
208 connect(ui->view_log->horizontalHeader(), SIGNAL(sectionResized(int,int,int)), this, SLOT(logViewSectionSizeChanged(int,int,int)));
210 //Create context menu
211 m_contextMenu = new QMenu();
212 QAction *contextMenuDetailsAction = m_contextMenu->addAction(QIcon(":/icons/zoom.png"), tr("Show details for selected job"));
213 QAction *contextMenuShowFileAction = m_contextMenu->addAction(QIcon(":/icons/folder_go.png"), tr("Browse Output File Location"));
214 m_contextMenu->addSeparator();
216 //Create "filter" context menu
217 m_progressViewFilterGroup = new QActionGroup(this);
218 QAction *contextMenuFilterAction[5] = {NULL, NULL, NULL, NULL, NULL};
219 if(QMenu *filterMenu = m_contextMenu->addMenu(QIcon(":/icons/filter.png"), tr("Filter Log Items")))
221 contextMenuFilterAction[0] = filterMenu->addAction(m_progressModel->getIcon(ProgressModel::JobRunning), tr("Show Running Only"));
222 contextMenuFilterAction[1] = filterMenu->addAction(m_progressModel->getIcon(ProgressModel::JobComplete), tr("Show Succeeded Only"));
223 contextMenuFilterAction[2] = filterMenu->addAction(m_progressModel->getIcon(ProgressModel::JobFailed), tr("Show Failed Only"));
224 contextMenuFilterAction[3] = filterMenu->addAction(m_progressModel->getIcon(ProgressModel::JobSkipped), tr("Show Skipped Only"));
225 contextMenuFilterAction[4] = filterMenu->addAction(m_progressModel->getIcon(ProgressModel::JobState(-1)), tr("Show All Items"));
226 if(QAction *act = contextMenuFilterAction[0]) { m_progressViewFilterGroup->addAction(act); act->setCheckable(true); act->setData(ProgressModel::JobRunning); }
227 if(QAction *act = contextMenuFilterAction[1]) { m_progressViewFilterGroup->addAction(act); act->setCheckable(true); act->setData(ProgressModel::JobComplete); }
228 if(QAction *act = contextMenuFilterAction[2]) { m_progressViewFilterGroup->addAction(act); act->setCheckable(true); act->setData(ProgressModel::JobFailed); }
229 if(QAction *act = contextMenuFilterAction[3]) { m_progressViewFilterGroup->addAction(act); act->setCheckable(true); act->setData(ProgressModel::JobSkipped); }
230 if(QAction *act = contextMenuFilterAction[4]) { m_progressViewFilterGroup->addAction(act); act->setCheckable(true); act->setData(-1); act->setChecked(true); }
234 if(m_filterInfoLabel = new QLabel(ui->view_log))
236 m_filterInfoLabel->setFrameShape(QFrame::NoFrame);
237 m_filterInfoLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
238 m_filterInfoLabel->setUserData(0, new IntUserData(-1));
239 SET_FONT_BOLD(m_filterInfoLabel, true);
240 SET_TEXT_COLOR(m_filterInfoLabel, Qt::darkGray);
241 m_filterInfoLabel->setContextMenuPolicy(Qt::CustomContextMenu);
242 connect(m_filterInfoLabel, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenuTriggered(QPoint)));
243 m_filterInfoLabel->hide();
245 if(m_filterInfoLabelIcon = new QLabel(ui->view_log))
247 m_filterInfoLabelIcon->setFrameShape(QFrame::NoFrame);
248 m_filterInfoLabelIcon->setAlignment(Qt::AlignHCenter | Qt::AlignTop);
249 m_filterInfoLabelIcon->setContextMenuPolicy(Qt::CustomContextMenu);
250 const QIcon &ico = m_progressModel->getIcon(ProgressModel::JobState(-1));
251 m_filterInfoLabelIcon->setPixmap(ico.pixmap(16, 16));
252 connect(m_filterInfoLabelIcon, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenuTriggered(QPoint)));
253 m_filterInfoLabelIcon->hide();
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++)
263 if(contextMenuFilterAction[i]) connect(contextMenuFilterAction[i], SIGNAL(triggered(bool)), this, SLOT(contextMenuFilterActionTriggered()));
265 SET_FONT_BOLD(contextMenuDetailsAction, true);
270 for(int i = 0; i < fileListModel->rowCount(); i++)
272 m_pendingJobs.append(fileListModel->getFile(fileListModel->index(i,0)));
277 ui->label_headerStatus->setText(QString("<b>%1</b><br>%2").arg(tr("Encoding Files"), tr("Your files are being encoded, please be patient...")));
279 //Enable system tray icon
280 connect(m_systemTray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(systemTrayActivated(QSystemTrayIcon::ActivationReason)));
283 m_runningThreads = 0;
286 m_succeededJobs.clear();
287 m_failedJobs.clear();
288 m_skippedJobs.clear();
289 m_userAborted = false;
290 m_forcedAbort = false;
294 ////////////////////////////////////////////////////////////
296 ////////////////////////////////////////////////////////////
298 ProcessingDialog::~ProcessingDialog(void)
300 ui->view_log->setModel(NULL);
302 if(m_progressIndicator)
304 m_progressIndicator->stop();
309 m_diskObserver->stop();
310 if(!m_diskObserver->wait(15000))
312 m_diskObserver->terminate();
313 m_diskObserver->wait();
319 m_cpuObserver->stop();
320 if(!m_cpuObserver->wait(15000))
322 m_cpuObserver->terminate();
323 m_cpuObserver->wait();
329 m_ramObserver->stop();
330 if(!m_ramObserver->wait(15000))
332 m_ramObserver->terminate();
333 m_ramObserver->wait();
339 if(!m_threadPool->waitForDone(100))
341 emit abortRunningTasks();
342 m_threadPool->waitForDone();
346 MUTILS_DELETE(m_progressIndicator);
347 MUTILS_DELETE(m_systemTray);
348 MUTILS_DELETE(m_diskObserver);
349 MUTILS_DELETE(m_cpuObserver);
350 MUTILS_DELETE(m_ramObserver);
351 MUTILS_DELETE(m_progressViewFilterGroup);
352 MUTILS_DELETE(m_filterInfoLabel);
353 MUTILS_DELETE(m_filterInfoLabelIcon);
354 MUTILS_DELETE(m_contextMenu);
355 MUTILS_DELETE(m_progressModel);
356 MUTILS_DELETE(m_threadPool);
357 MUTILS_DELETE(m_defaultColor);
359 WinSevenTaskbar::setOverlayIcon(this, NULL);
360 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNoState);
364 lamexp_free_window_icon(m_windowIcon);
371 ////////////////////////////////////////////////////////////
373 ////////////////////////////////////////////////////////////
375 void ProcessingDialog::showEvent(QShowEvent *event)
377 QDialog::showEvent(event);
381 static const char *NA = " N/A";
383 lamexp_enable_close_button(this, false);
384 ui->button_closeDialog->setEnabled(false);
385 ui->button_AbortProcess->setEnabled(false);
386 m_progressIndicator->start();
387 m_systemTray->setVisible(true);
389 lamexp_change_process_priority(1);
391 ui->label_cpu->setText(NA);
392 ui->label_disk->setText(NA);
393 ui->label_ram->setText(NA);
395 QTimer::singleShot(500, this, SLOT(initEncoding()));
399 //Force update geometry
403 void ProcessingDialog::closeEvent(QCloseEvent *event)
405 if(!ui->button_closeDialog->isEnabled())
411 m_systemTray->setVisible(false);
415 bool ProcessingDialog::eventFilter(QObject *obj, QEvent *event)
417 if(obj == ui->label_versionInfo)
419 if(event->type() == QEvent::Enter)
421 QPalette palette = ui->label_versionInfo->palette();
422 *m_defaultColor = palette.color(QPalette::Normal, QPalette::WindowText);
423 palette.setColor(QPalette::Normal, QPalette::WindowText, Qt::red);
424 ui->label_versionInfo->setPalette(palette);
426 else if(event->type() == QEvent::Leave)
428 QPalette palette = ui->label_versionInfo->palette();
429 palette.setColor(QPalette::Normal, QPalette::WindowText, *m_defaultColor);
430 ui->label_versionInfo->setPalette(palette);
432 else if(event->type() == QEvent::MouseButtonPress)
434 QUrl url(lamexp_website_url());
435 QDesktopServices::openUrl(url);
442 bool ProcessingDialog::event(QEvent *e)
446 case lamexp_event_queryendsession:
447 qWarning("System is shutting down, preparing to abort...");
448 if(!m_userAborted) abortEncoding(true);
450 case lamexp_event_endsession:
451 qWarning("System is shutting down, encoding will be aborted now...");
456 if(!m_userAborted) abortEncoding(true);
457 qApp->processEvents(QEventLoop::WaitForMoreEvents | QEventLoop::ExcludeUserInputEvents);
460 m_pendingJobs.clear();
463 return QDialog::event(e);
470 void ProcessingDialog::resizeEvent(QResizeEvent *event)
472 if(event) QDialog::resizeEvent(event);
474 if(QWidget *port = ui->view_log->viewport())
476 QRect geom = port->geometry();
477 m_filterInfoLabel->setGeometry(geom.left() + 16, geom.top() + 16, geom.width() - 32, 48);
478 m_filterInfoLabelIcon->setGeometry(geom.left() + 16, geom.top() + 64, geom.width() - 32, geom.height() - 80);
482 bool ProcessingDialog::winEvent(MSG *message, long *result)
484 return WinSevenTaskbar::handleWinEvent(message, result);
487 ////////////////////////////////////////////////////////////
489 ////////////////////////////////////////////////////////////
491 void ProcessingDialog::initEncoding(void)
493 qDebug("Initializing encoding process...");
495 m_runningThreads = 0;
498 m_succeededJobs.clear();
499 m_failedJobs.clear();
500 m_skippedJobs.clear();
501 m_userAborted = false;
502 m_forcedAbort = false;
505 DecoderRegistry::configureDecoders(m_settings);
507 CHANGE_BACKGROUND_COLOR(ui->frame_header, QColor(Qt::white));
508 SET_PROGRESS_TEXT(tr("Encoding files, please wait..."));
510 ui->button_closeDialog->setEnabled(false);
511 ui->button_AbortProcess->setEnabled(true);
512 ui->progressBar->setRange(0, m_pendingJobs.count());
513 ui->checkBox_shutdownComputer->setEnabled(true);
514 ui->checkBox_shutdownComputer->setChecked(false);
516 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
517 WinSevenTaskbar::setTaskbarProgress(this, 0, m_pendingJobs.count());
518 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/control_play_blue.png"));
522 m_diskObserver = new DiskObserverThread(m_settings->customTempPathEnabled() ? m_settings->customTempPath() : MUtils::temp_folder());
523 connect(m_diskObserver, SIGNAL(messageLogged(QString,int)), m_progressModel, SLOT(addSystemMessage(QString,int)), Qt::QueuedConnection);
524 connect(m_diskObserver, SIGNAL(freeSpaceChanged(quint64)), this, SLOT(diskUsageHasChanged(quint64)), Qt::QueuedConnection);
525 m_diskObserver->start();
529 m_cpuObserver = new CPUObserverThread();
530 connect(m_cpuObserver, SIGNAL(currentUsageChanged(double)), this, SLOT(cpuUsageHasChanged(double)), Qt::QueuedConnection);
531 m_cpuObserver->start();
535 m_ramObserver = new RAMObserverThread();
536 connect(m_ramObserver, SIGNAL(currentUsageChanged(double)), this, SLOT(ramUsageHasChanged(double)), Qt::QueuedConnection);
537 m_ramObserver->start();
542 unsigned int maximumInstances = qBound(0U, m_settings->maximumInstances(), MAX_INSTANCES);
543 if(maximumInstances < 1)
545 lamexp_cpu_t cpuFeatures = lamexp_detect_cpu_features(lamexp_arguments());
546 maximumInstances = cores2instances(qBound(1, cpuFeatures.count, 64));
549 maximumInstances = qBound(1U, maximumInstances, static_cast<unsigned int>(m_pendingJobs.count()));
550 if(maximumInstances > 1)
552 m_progressModel->addSystemMessage(tr("Multi-threading enabled: Running %1 instances in parallel!").arg(QString::number(maximumInstances)));
555 m_threadPool = new QThreadPool();
556 m_threadPool->setMaxThreadCount(maximumInstances);
559 //for(int i = 0; i < m_threadPool->maxThreadCount(); i++)
562 // qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
563 // QThread::yieldCurrentThread();
566 m_initThreads = m_threadPool->maxThreadCount();
567 QTimer::singleShot(100, this, SLOT(initNextJob()));
568 m_timerStart = lamexp_perfcounter_value();
571 void ProcessingDialog::initNextJob(void)
573 if((m_initThreads > 0) && (!m_userAborted))
576 if(--m_initThreads > 0)
578 QTimer::singleShot(100, this, SLOT(initNextJob()));
583 void ProcessingDialog::startNextJob(void)
585 if(m_pendingJobs.isEmpty())
587 qWarning("No more files left, unable to start another job!");
594 AudioFileModel currentFile = updateMetaInfo(m_pendingJobs.takeFirst());
595 bool nativeResampling = false;
597 //Create encoder instance
598 AbstractEncoder *encoder = EncoderRegistry::createInstance(m_settings->compressionEncoder(), m_settings, &nativeResampling);
600 //Create processing thread
601 ProcessThread *thread = new ProcessThread
604 (m_settings->outputToSourceDir() ? QFileInfo(currentFile.filePath()).absolutePath() : m_settings->outputDir()),
605 (m_settings->customTempPathEnabled() ? m_settings->customTempPath() : MUtils::temp_folder()),
607 m_settings->prependRelativeSourcePath() && (!m_settings->outputToSourceDir())
611 if(m_settings->forceStereoDownmix())
613 thread->addFilter(new DownmixFilter());
615 if((m_settings->samplingRate() > 0) && !nativeResampling)
617 if(SettingsModel::samplingRates[m_settings->samplingRate()] != currentFile.techInfo().audioSamplerate() || currentFile.techInfo().audioSamplerate() == 0)
619 thread->addFilter(new ResampleFilter(SettingsModel::samplingRates[m_settings->samplingRate()]));
622 if((m_settings->toneAdjustBass() != 0) || (m_settings->toneAdjustTreble() != 0))
624 thread->addFilter(new ToneAdjustFilter(m_settings->toneAdjustBass(), m_settings->toneAdjustTreble()));
626 if(m_settings->normalizationFilterEnabled())
628 thread->addFilter(new NormalizeFilter(m_settings->normalizationFilterMaxVolume(), m_settings->normalizationFilterEQMode()));
630 if(m_settings->renameOutputFilesEnabled() && (!m_settings->renameOutputFilesPattern().simplified().isEmpty()))
632 thread->setRenamePattern(m_settings->renameOutputFilesPattern());
634 if(m_settings->overwriteMode() != SettingsModel::Overwrite_KeepBoth)
636 thread->setOverwriteMode((m_settings->overwriteMode() == SettingsModel::Overwrite_SkipFile), (m_settings->overwriteMode() == SettingsModel::Overwrite_Replaces));
639 m_allJobs.append(thread->getId());
641 //Connect thread signals
642 connect(thread, SIGNAL(processFinished()), this, SLOT(doneEncoding()), Qt::QueuedConnection);
643 connect(thread, SIGNAL(processStateInitialized(QUuid,QString,QString,int)), m_progressModel, SLOT(addJob(QUuid,QString,QString,int)), Qt::QueuedConnection);
644 connect(thread, SIGNAL(processStateChanged(QUuid,QString,int)), m_progressModel, SLOT(updateJob(QUuid,QString,int)), Qt::QueuedConnection);
645 connect(thread, SIGNAL(processStateFinished(QUuid,QString,int)), this, SLOT(processFinished(QUuid,QString,int)), Qt::QueuedConnection);
646 connect(thread, SIGNAL(processMessageLogged(QUuid,QString)), m_progressModel, SLOT(appendToLog(QUuid,QString)), Qt::QueuedConnection);
647 connect(this, SIGNAL(abortRunningTasks()), thread, SLOT(abort()), Qt::DirectConnection);
649 //Initialize thread object
652 qFatal("Fatal Error: Thread initialization has failed!");
656 if(!thread->start(m_threadPool))
658 qWarning("Job failed to start or file was skipped!");
662 void ProcessingDialog::abortEncoding(bool force)
664 m_userAborted = true;
665 if(force) m_forcedAbort = true;
666 ui->button_AbortProcess->setEnabled(false);
667 SET_PROGRESS_TEXT(tr("Aborted! Waiting for running jobs to terminate..."));
668 emit abortRunningTasks();
671 void ProcessingDialog::doneEncoding(void)
674 ui->progressBar->setValue(ui->progressBar->value() + 1);
678 SET_PROGRESS_TEXT(tr("Encoding: %n file(s) of %1 completed so far, please wait...", "", ui->progressBar->value()).arg(QString::number(ui->progressBar->maximum())));
679 WinSevenTaskbar::setTaskbarProgress(this, ui->progressBar->value(), ui->progressBar->maximum());
682 if((!m_pendingJobs.isEmpty()) && (!m_userAborted))
684 QTimer::singleShot(0, this, SLOT(startNextJob()));
685 qDebug("%d files left, starting next job...", m_pendingJobs.count());
689 if(m_runningThreads > 0)
691 qDebug("No files left, but still have %u running jobs.", m_runningThreads);
695 QApplication::setOverrideCursor(Qt::WaitCursor);
696 qDebug("Running jobs: %u", m_runningThreads);
698 if(!m_userAborted && m_settings->createPlaylist() && !m_settings->outputToSourceDir())
700 SET_PROGRESS_TEXT(tr("Creating the playlist file, please wait..."));
701 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
707 CHANGE_BACKGROUND_COLOR(ui->frame_header, QColor("#FFFFE0"));
708 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
709 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/error.png"));
710 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!"));
711 m_systemTray->showMessage(tr("LameXP - Aborted"), tr("Process was aborted by the user."), QSystemTrayIcon::Warning);
712 m_systemTray->setIcon(QIcon(":/icons/cd_delete.png"));
713 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
714 if(!m_forcedAbort) PLAY_SOUND_OPTIONAL("aborted", false);
718 const __int64 counter = lamexp_perfcounter_value();
719 const __int64 frequency = lamexp_perfcounter_frequ();
720 if((counter >= 0I64) && (frequency >= 0))
722 if((m_timerStart >= 0I64) && (m_timerStart < counter))
724 double timeElapsed = static_cast<double>(counter - m_timerStart) / static_cast<double>(frequency);
725 m_progressModel->addSystemMessage(tr("Process finished after %1.").arg(time2text(timeElapsed)), ProgressModel::SysMsg_Performance);
729 if(m_failedJobs.count() > 0)
731 CHANGE_BACKGROUND_COLOR(ui->frame_header, QColor("#FFF0F0"));
732 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
733 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/exclamation.png"));
734 if(m_skippedJobs.count() > 0)
736 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())));
740 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())));
742 m_systemTray->showMessage(tr("LameXP - Error"), tr("At least one file has failed!"), QSystemTrayIcon::Critical);
743 m_systemTray->setIcon(QIcon(":/icons/cd_delete.png"));
744 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
745 PLAY_SOUND_OPTIONAL("error", false);
749 CHANGE_BACKGROUND_COLOR(ui->frame_header, QColor("#F0FFF0"));
750 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
751 WinSevenTaskbar::setOverlayIcon(this, &QIcon(":/icons/accept.png"));
752 if(m_skippedJobs.count() > 0)
754 SET_PROGRESS_TEXT(tr("All files completed successfully. Skipped %n file(s).", "", m_skippedJobs.count()));
758 SET_PROGRESS_TEXT(tr("All files completed successfully."));
760 m_systemTray->showMessage(tr("LameXP - Done"), tr("All files completed successfully."), QSystemTrayIcon::Information);
761 m_systemTray->setIcon(QIcon(":/icons/cd_add.png"));
762 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
763 PLAY_SOUND_OPTIONAL("success", false);
767 lamexp_enable_close_button(this, true);
768 ui->button_closeDialog->setEnabled(true);
769 ui->button_AbortProcess->setEnabled(false);
770 ui->checkBox_shutdownComputer->setEnabled(false);
772 m_progressModel->restoreHiddenItems();
773 ui->view_log->scrollToBottom();
774 m_progressIndicator->stop();
775 ui->progressBar->setValue(ui->progressBar->maximum());
776 WinSevenTaskbar::setTaskbarProgress(this, ui->progressBar->value(), ui->progressBar->maximum());
778 QApplication::restoreOverrideCursor();
780 if(!m_userAborted && ui->checkBox_shutdownComputer->isChecked())
782 if(shutdownComputer())
784 m_shutdownFlag = m_settings->hibernateComputer() ? shutdownFlag_Hibernate : shutdownFlag_TurnPowerOff;
790 void ProcessingDialog::processFinished(const QUuid &jobId, const QString &outFileName, int success)
794 m_playList.insert(jobId, outFileName);
795 m_succeededJobs.append(jobId);
799 m_playList.insert(jobId, outFileName);
800 m_skippedJobs.append(jobId);
804 m_failedJobs.append(jobId);
807 //Update filter as soon as a job finished!
808 if(m_progressViewFilter >= 0)
810 QTimer::singleShot(0, this, SLOT(progressViewFilterChanged()));
814 void ProcessingDialog::progressModelChanged(void)
816 //Update filter as soon as the model changes!
817 if(m_progressViewFilter >= 0)
819 QTimer::singleShot(0, this, SLOT(progressViewFilterChanged()));
822 QTimer::singleShot(0, ui->view_log, SLOT(scrollToBottom()));
825 void ProcessingDialog::logViewDoubleClicked(const QModelIndex &index)
827 if(m_runningThreads == 0)
829 const QStringList &logFile = m_progressModel->getLogFile(index);
831 if(!logFile.isEmpty())
833 LogViewDialog *logView = new LogViewDialog(this);
834 logView->setWindowTitle(QString("LameXP - [%1]").arg(m_progressModel->data(index, Qt::DisplayRole).toString()));
835 logView->exec(logFile);
836 MUTILS_DELETE(logView);
840 QMessageBox::information(this, windowTitle(), m_progressModel->data(m_progressModel->index(index.row(), 0)).toString());
845 lamexp_beep(lamexp_beep_warning);
849 void ProcessingDialog::logViewSectionSizeChanged(int logicalIndex, int oldSize, int newSize)
851 if(logicalIndex == 1)
853 if(QHeaderView *hdr = ui->view_log->horizontalHeader())
855 hdr->setMinimumSectionSize(qMax(hdr->minimumSectionSize(), hdr->sectionSize(1)));
860 void ProcessingDialog::contextMenuTriggered(const QPoint &pos)
862 QAbstractScrollArea *scrollArea = dynamic_cast<QAbstractScrollArea*>(QObject::sender());
863 QWidget *sender = scrollArea ? scrollArea->viewport() : dynamic_cast<QWidget*>(QObject::sender());
865 if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0)
867 m_contextMenu->popup(sender->mapToGlobal(pos));
871 void ProcessingDialog::contextMenuDetailsActionTriggered(void)
873 QModelIndex index = ui->view_log->indexAt(ui->view_log->viewport()->mapFromGlobal(m_contextMenu->pos()));
874 logViewDoubleClicked(index.isValid() ? index : ui->view_log->currentIndex());
877 void ProcessingDialog::contextMenuShowFileActionTriggered(void)
879 QModelIndex index = ui->view_log->indexAt(ui->view_log->viewport()->mapFromGlobal(m_contextMenu->pos()));
880 const QUuid &jobId = m_progressModel->getJobId(index.isValid() ? index : ui->view_log->currentIndex());
881 QString filePath = m_playList.value(jobId, QString());
883 if(filePath.isEmpty())
885 lamexp_beep(lamexp_beep_warning);
889 if(QFileInfo(filePath).exists())
891 QString systemRootPath;
893 QDir systemRoot(lamexp_known_folder(lamexp_folder_systemfolder));
894 if(systemRoot.exists() && systemRoot.cdUp())
896 systemRootPath = systemRoot.canonicalPath();
899 if(!systemRootPath.isEmpty())
901 QFileInfo explorer(QString("%1/explorer.exe").arg(systemRootPath));
902 if(explorer.exists() && explorer.isFile())
904 QProcess::execute(explorer.canonicalFilePath(), QStringList() << "/select," << QDir::toNativeSeparators(QFileInfo(filePath).canonicalFilePath()));
910 qWarning("SystemRoot directory could not be detected!");
915 qWarning("File not found: %s", filePath.toLatin1().constData());
916 lamexp_beep(lamexp_beep_error);
920 void ProcessingDialog::contextMenuFilterActionTriggered(void)
922 if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
924 if(action->data().type() == QVariant::Int)
926 m_progressViewFilter = action->data().toInt();
927 progressViewFilterChanged();
928 QTimer::singleShot(0, this, SLOT(progressViewFilterChanged()));
929 QTimer::singleShot(0, ui->view_log, SLOT(scrollToBottom()));
930 action->setChecked(true);
936 * Filter progress items
938 void ProcessingDialog::progressViewFilterChanged(void)
940 bool matchFound = false;
942 for(int i = 0; i < ui->view_log->model()->rowCount(); i++)
944 QModelIndex index = (m_progressViewFilter >= 0) ? m_progressModel->index(i, 0) : QModelIndex();
945 const bool bHide = index.isValid() ? (m_progressModel->getJobState(index) != m_progressViewFilter) : false;
946 ui->view_log->setRowHidden(i, bHide); matchFound = matchFound || (!bHide);
949 if((m_progressViewFilter >= 0) && (!matchFound))
951 if(m_filterInfoLabel->isHidden() || (dynamic_cast<IntUserData*>(m_filterInfoLabel->userData(0))->value() != m_progressViewFilter))
953 dynamic_cast<IntUserData*>(m_filterInfoLabel->userData(0))->setValue(m_progressViewFilter);
954 m_filterInfoLabel->setText(QString("<p>» %1 «</p>").arg(tr("None of the items matches the current filtering rules")));
955 m_filterInfoLabel->show();
956 m_filterInfoLabelIcon->setPixmap(m_progressModel->getIcon(static_cast<ProgressModel::JobState>(m_progressViewFilter)).pixmap(16, 16, QIcon::Disabled));
957 m_filterInfoLabelIcon->show();
961 else if(!m_filterInfoLabel->isHidden())
963 m_filterInfoLabel->hide();
964 m_filterInfoLabelIcon->hide();
968 ////////////////////////////////////////////////////////////
970 ////////////////////////////////////////////////////////////
972 void ProcessingDialog::writePlayList(void)
974 if(m_succeededJobs.count() <= 0 || m_allJobs.count() <= 0)
976 qWarning("WritePlayList: Nothing to do!");
980 //Init local variables
982 QRegExp regExp1("\\[\\d\\d\\][^/\\\\]+$", Qt::CaseInsensitive);
983 QRegExp regExp2("\\(\\d\\d\\)[^/\\\\]+$", Qt::CaseInsensitive);
984 QRegExp regExp3("\\d\\d[^/\\\\]+$", Qt::CaseInsensitive);
985 bool usePrefix[3] = {true, true, true};
986 bool useUtf8 = false;
989 //Generate playlist name
990 QString playListName = (m_metaInfo->album().isEmpty() ? "Playlist" : m_metaInfo->album());
991 if(!m_metaInfo->artist().isEmpty())
993 playListName = QString("%1 - %2").arg(m_metaInfo->artist(), playListName);
996 //Clean playlist name
997 playListName = lamexp_clean_filename(playListName);
999 //Create list of audio files
1000 for(int i = 0; i < m_allJobs.count(); i++)
1002 if(!m_succeededJobs.contains(m_allJobs.at(i))) continue;
1003 list << QDir::toNativeSeparators(QDir(m_settings->outputDir()).relativeFilePath(m_playList.value(m_allJobs.at(i), "N/A")));
1007 for(int i = 0; i < list.count(); i++)
1009 if(regExp1.indexIn(list.at(i)) < 0) usePrefix[0] = false;
1010 if(regExp2.indexIn(list.at(i)) < 0) usePrefix[1] = false;
1011 if(regExp3.indexIn(list.at(i)) < 0) usePrefix[2] = false;
1013 if(usePrefix[0] || usePrefix[1] || usePrefix[2])
1015 playListName.prepend(usePrefix[0] ? "[00] " : (usePrefix[1] ? "(00) " : "00 "));
1018 //Do we need an UTF-8 playlist?
1019 for(int i = 0; i < list.count(); i++)
1021 if(wcscmp(MUTILS_WCHR(QString::fromLatin1(list.at(i).toLatin1().constData())), MUTILS_WCHR(list.at(i))))
1028 //Generate playlist output file
1029 QString playListFile = QString("%1/%2.%3").arg(m_settings->outputDir(), playListName, (useUtf8 ? "m3u8" : "m3u"));
1030 while(QFileInfo(playListFile).exists())
1032 playListFile = QString("%1/%2 (%3).%4").arg(m_settings->outputDir(), playListName, QString::number(++counter), (useUtf8 ? "m3u8" : "m3u"));
1035 //Now write playlist to output file
1036 QFile playList(playListFile);
1037 if(playList.open(QIODevice::WriteOnly))
1041 playList.write("\xef\xbb\xbf");
1043 playList.write("#EXTM3U\r\n");
1044 while(!list.isEmpty())
1046 playList.write(useUtf8 ? MUTILS_UTF8(list.takeFirst()) : list.takeFirst().toLatin1().constData());
1047 playList.write("\r\n");
1053 QMessageBox::warning(this, tr("Playlist creation failed"), QString("%1<br><nobr>%2</nobr>").arg(tr("The playlist file could not be created:"), playListFile));
1057 AudioFileModel ProcessingDialog::updateMetaInfo(AudioFileModel &audioFile)
1059 if(!m_settings->writeMetaTags())
1061 audioFile.metaInfo().reset();
1065 audioFile.metaInfo().update(*m_metaInfo, true);
1067 if(audioFile.metaInfo().position() == UINT_MAX)
1069 audioFile.metaInfo().setPosition(m_currentFile);
1075 void ProcessingDialog::systemTrayActivated(QSystemTrayIcon::ActivationReason reason)
1077 if(reason == QSystemTrayIcon::DoubleClick)
1079 lamexp_bring_to_front(this);
1083 void ProcessingDialog::cpuUsageHasChanged(const double val)
1086 ui->label_cpu->setText(QString().sprintf(" %d%%", qRound(val * 100.0)));
1087 UPDATE_MIN_WIDTH(ui->label_cpu);
1090 void ProcessingDialog::ramUsageHasChanged(const double val)
1093 ui->label_ram->setText(QString().sprintf(" %d%%", qRound(val * 100.0)));
1094 UPDATE_MIN_WIDTH(ui->label_ram);
1097 void ProcessingDialog::diskUsageHasChanged(const quint64 val)
1100 const char *postfixStr[6] = {"B", "KB", "MB", "GB", "TB", "PB"};
1101 double space = static_cast<double>(val);
1103 while((space >= 1000.0) && (postfix < 5))
1105 space = space / 1024.0;
1109 ui->label_disk->setText(QString().sprintf(" %3.1f %s", space, postfixStr[postfix]));
1110 UPDATE_MIN_WIDTH(ui->label_disk);
1113 bool ProcessingDialog::shutdownComputer(void)
1115 const int iTimeout = m_settings->hibernateComputer() ? 10 : 30;
1116 const Qt::WindowFlags flags = Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowSystemMenuHint;
1117 const QString text = QString("%1%2%1").arg(QString().fill(' ', 18), tr("Warning: Computer will shutdown in %1 seconds..."));
1119 qWarning("Initiating shutdown sequence!");
1121 QProgressDialog progressDialog(text.arg(iTimeout), tr("Cancel Shutdown"), 0, iTimeout + 1, this, flags);
1122 QPushButton *cancelButton = new QPushButton(tr("Cancel Shutdown"), &progressDialog);
1123 cancelButton->setIcon(QIcon(":/icons/power_on.png"));
1124 progressDialog.setModal(true);
1125 progressDialog.setAutoClose(false);
1126 progressDialog.setAutoReset(false);
1127 progressDialog.setWindowIcon(QIcon(":/icons/power_off.png"));
1128 progressDialog.setCancelButton(cancelButton);
1129 progressDialog.show();
1131 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1133 QApplication::setOverrideCursor(Qt::WaitCursor);
1134 PLAY_SOUND_OPTIONAL("shutdown", false);
1135 QApplication::restoreOverrideCursor();
1138 timer.setInterval(1000);
1141 QEventLoop eventLoop(this);
1142 connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
1143 connect(&progressDialog, SIGNAL(canceled()), &eventLoop, SLOT(quit()));
1145 for(int i = 1; i <= iTimeout; i++)
1148 if(progressDialog.wasCanceled())
1150 progressDialog.close();
1153 progressDialog.setValue(i+1);
1154 progressDialog.setLabelText(text.arg(iTimeout-i));
1155 if(iTimeout-i == 3) progressDialog.setCancelButton(NULL);
1156 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1157 PLAY_SOUND_OPTIONAL(((i < iTimeout) ? "beep" : "beep2"), false);
1160 progressDialog.close();
1164 QString ProcessingDialog::time2text(const double timeVal) const
1167 double frcPart = modf(timeVal, &intPart);
1169 QTime time = QTime().addSecs(qRound(intPart)).addMSecs(qRound(frcPart * 1000.0));
1175 a = tr("%n hour(s)", "", time.hour());
1176 b = tr("%n minute(s)", "", time.minute());
1178 else if(time.minute() > 0)
1180 a = tr("%n minute(s)", "", time.minute());
1181 b = tr("%n second(s)", "", time.second());
1185 a = tr("%n second(s)", "", time.second());
1186 b = tr("%n millisecond(s)", "", time.msec());
1189 return QString("%1, %2").arg(a, b);
1192 ////////////////////////////////////////////////////////////
1194 ////////////////////////////////////////////////////////////
1196 static int cores2instances(int cores)
1198 //This function is a "cubic spline" with sampling points at:
1199 //(1,1); (2,2); (4,4); (8,6); (16,8); (32,11); (64,16)
1200 static const double LUT[8][5] =
1202 { 1.0, 0.014353554, -0.043060662, 1.028707108, 0.000000000},
1203 { 2.0, -0.028707108, 0.215303309, 0.511979167, 0.344485294},
1204 { 4.0, 0.010016468, -0.249379596, 2.370710784, -2.133823529},
1205 { 8.0, 0.000282437, -0.015762868, 0.501776961, 2.850000000},
1206 {16.0, 0.000033270, -0.003802849, 0.310416667, 3.870588235},
1207 {32.0, 0.000006343, -0.001217831, 0.227696078, 4.752941176},
1208 {64.0, 0.000000000, 0.000000000, 0.000000000, 16.000000000},
1209 {DBL_MAX, 0.0, 0.0, 0.0, 0.0}
1212 double x = abs(static_cast<double>(cores)), y = 1.0;
1214 for(size_t i = 0; i < 7; i++)
1216 if((x >= LUT[i][0]) && (x < LUT[i+1][0]))
1218 y = (((((LUT[i][1] * x) + LUT[i][2]) * x) + LUT[i][3]) * x) + LUT[i][4];