1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2018 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 "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"
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>
55 #include <QApplication>
57 #include <QDesktopWidget>
59 #include <QMessageBox>
61 #include <QCloseEvent>
62 #include <QDesktopServices>
68 #include <QSystemTrayIcon>
70 #include <QProgressDialog>
71 #include <QResizeEvent>
73 #include <QElapsedTimer>
74 #include <QThreadPool>
80 //Maximum number of parallel instances
81 #define MAX_INSTANCES 64U
83 ////////////////////////////////////////////////////////////
85 #define CHANGE_BACKGROUND_COLOR(WIDGET, COLOR) do \
87 QPalette palette = WIDGET->palette(); \
88 palette.setColor(QPalette::Background, COLOR); \
89 WIDGET->setPalette(palette); \
93 #define SET_PROGRESS_TEXT(TXT) do \
95 ui->label_progress->setText(TXT); \
96 if(!m_systemTray.isNull()) \
98 if(!m_systemTray->isVisible()) m_systemTray->setVisible(true); \
99 m_systemTray->setToolTip(QString().sprintf("LameXP v%d.%02d\n%ls", lamexp_version_major(), lamexp_version_minor(), QString(TXT).utf16())); \
104 #define SET_FONT_BOLD(WIDGET,BOLD) do \
106 QFont _font = WIDGET->font(); \
107 _font.setBold(BOLD); WIDGET->setFont(_font); \
111 #define SET_TEXT_COLOR(WIDGET, COLOR) do \
113 QPalette _palette = WIDGET->palette(); \
114 _palette.setColor(QPalette::WindowText, (COLOR)); \
115 _palette.setColor(QPalette::Text, (COLOR)); \
116 WIDGET->setPalette(_palette); \
120 #define UPDATE_MIN_WIDTH(WIDGET) do \
122 if(WIDGET->width() > WIDGET->minimumWidth()) WIDGET->setMinimumWidth(WIDGET->width()); \
126 #define PLAY_SOUND_OPTIONAL(NAME, ASYNC) do \
128 if(m_settings->soundsEnabled()) MUtils::Sound::play_sound((NAME), (ASYNC)); \
132 #define IS_VBR(RC_MODE) ((RC_MODE) == SettingsModel::VBRMode)
134 ////////////////////////////////////////////////////////////
136 //Dummy class for UserData
137 class IntUserData
: public QObjectUserData
140 IntUserData(int value
) : m_value(value
) {/*NOP*/}
141 int value(void) { return m_value
; }
142 void setValue(int value
) { m_value
= value
; }
147 ////////////////////////////////////////////////////////////
149 ////////////////////////////////////////////////////////////
151 ProcessingDialog::ProcessingDialog(FileListModel
*const fileListModel
, const AudioFileModel_MetaInfo
*const metaInfo
, const SettingsModel
*const settings
, QWidget
*const parent
)
154 ui(new Ui::ProcessingDialog
),
155 m_systemTray(new QSystemTrayIcon(QIcon(":/icons/cd_go.png"), this)),
156 m_taskbar(new MUtils::Taskbar7(this)),
157 m_settings(settings
),
158 m_metaInfo(metaInfo
),
159 m_shutdownFlag(SHUTDOWN_FLAG_NONE
),
160 m_progressViewFilter(-1),
162 m_defaultColor(new QColor()),
163 m_tempFolder(settings
->customTempPathEnabled() ? settings
->customTempPath() : MUtils::temp_folder()),
166 //Init the dialog, from the .ui file
168 setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint
);
169 setMinimumSize(this->size());
171 //Update the window icon
172 MUtils::GUI::set_window_icon(this, lamexp_app_icon(), true);
175 ui
->label_headerIcon
->setPixmap(lamexp_app_icon().pixmap(ui
->label_headerIcon
->size()));
178 ui
->label_versionInfo
->setText(QString().sprintf("v%d.%02d %s (Build %d)", lamexp_version_major(), lamexp_version_minor(), lamexp_version_release(), lamexp_version_build()));
179 ui
->label_versionInfo
->installEventFilter(this);
182 qRegisterMetaType
<QUuid
>("QUuid");
184 //Adjust size to DPI settings and re-center
185 MUtils::GUI::scale_widget(this);
188 connect(ui
->button_AbortProcess
, SIGNAL(clicked()), this, SLOT(abortEncoding()));
190 //Init progress indicator
191 m_progressIndicator
.reset(new QMovie(":/images/Working.gif"));
192 m_progressIndicator
->setCacheMode(QMovie::CacheAll
);
193 ui
->label_headerWorking
->setMovie(m_progressIndicator
.data());
194 ui
->progressBar
->setValue(0);
196 //Init progress model
197 m_progressModel
.reset(new ProgressModel());
198 ui
->view_log
->setModel(m_progressModel
.data());
199 ui
->view_log
->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents
);
200 ui
->view_log
->verticalHeader()->hide();
201 ui
->view_log
->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents
);
202 ui
->view_log
->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch
);
203 ui
->view_log
->viewport()->installEventFilter(this);
204 connect(m_progressModel
.data(), SIGNAL(rowsInserted(QModelIndex
,int,int)), this, SLOT(progressModelChanged()));
205 connect(m_progressModel
.data(), SIGNAL(rowsMoved(QModelIndex
,int,int,QModelIndex
,int)), this, SLOT(progressModelChanged()));
206 connect(m_progressModel
.data(), SIGNAL(rowsRemoved(QModelIndex
,int,int)), this, SLOT(progressModelChanged()));
207 connect(m_progressModel
.data(), SIGNAL(modelReset()), this, SLOT(progressModelChanged()));
208 connect(ui
->view_log
, SIGNAL(activated(QModelIndex
)), this, SLOT(logViewDoubleClicked(QModelIndex
)));
209 connect(ui
->view_log
->horizontalHeader(), SIGNAL(sectionResized(int,int,int)), this, SLOT(logViewSectionSizeChanged(int,int,int)));
211 //Create context menu
212 m_contextMenu
.reset(new QMenu());
213 QAction
*contextMenuDetailsAction
= m_contextMenu
->addAction(QIcon(":/icons/zoom.png"), tr("Show details for selected job"));
214 QAction
*contextMenuShowFileAction
= m_contextMenu
->addAction(QIcon(":/icons/folder_go.png"), tr("Browse Output File Location"));
215 m_contextMenu
->addSeparator();
217 //Create "filter" context menu
218 m_progressViewFilterGroup
.reset(new QActionGroup(this));
219 QAction
*contextMenuFilterAction
[5] = {NULL
, NULL
, NULL
, NULL
, NULL
};
220 if(QMenu
*filterMenu
= m_contextMenu
->addMenu(QIcon(":/icons/filter.png"), tr("Filter Log Items")))
222 contextMenuFilterAction
[0] = filterMenu
->addAction(m_progressModel
->getIcon(ProgressModel::JobRunning
), tr("Show Running Only"));
223 contextMenuFilterAction
[1] = filterMenu
->addAction(m_progressModel
->getIcon(ProgressModel::JobComplete
), tr("Show Succeeded Only"));
224 contextMenuFilterAction
[2] = filterMenu
->addAction(m_progressModel
->getIcon(ProgressModel::JobFailed
), tr("Show Failed Only"));
225 contextMenuFilterAction
[3] = filterMenu
->addAction(m_progressModel
->getIcon(ProgressModel::JobSkipped
), tr("Show Skipped Only"));
226 contextMenuFilterAction
[4] = filterMenu
->addAction(m_progressModel
->getIcon(ProgressModel::JobState(-1)), tr("Show All Items"));
227 if(QAction
*act
= contextMenuFilterAction
[0]) { m_progressViewFilterGroup
->addAction(act
); act
->setCheckable(true); act
->setData(ProgressModel::JobRunning
); }
228 if(QAction
*act
= contextMenuFilterAction
[1]) { m_progressViewFilterGroup
->addAction(act
); act
->setCheckable(true); act
->setData(ProgressModel::JobComplete
); }
229 if(QAction
*act
= contextMenuFilterAction
[2]) { m_progressViewFilterGroup
->addAction(act
); act
->setCheckable(true); act
->setData(ProgressModel::JobFailed
); }
230 if(QAction
*act
= contextMenuFilterAction
[3]) { m_progressViewFilterGroup
->addAction(act
); act
->setCheckable(true); act
->setData(ProgressModel::JobSkipped
); }
231 if(QAction
*act
= contextMenuFilterAction
[4]) { m_progressViewFilterGroup
->addAction(act
); act
->setCheckable(true); act
->setData(-1); act
->setChecked(true); }
235 m_filterInfoLabel
.reset(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
.data(), SIGNAL(customContextMenuRequested(QPoint
)), this, SLOT(contextMenuTriggered(QPoint
)));
243 m_filterInfoLabel
->hide();
245 m_filterInfoLabelIcon
.reset(new QLabel(ui
->view_log
));
246 m_filterInfoLabelIcon
->setFrameShape(QFrame::NoFrame
);
247 m_filterInfoLabelIcon
->setAlignment(Qt::AlignHCenter
| Qt::AlignTop
);
248 m_filterInfoLabelIcon
->setContextMenuPolicy(Qt::CustomContextMenu
);
249 const QIcon
&ico
= m_progressModel
->getIcon(ProgressModel::JobState(-1));
250 m_filterInfoLabelIcon
->setPixmap(ico
.pixmap(16, 16));
251 connect(m_filterInfoLabelIcon
.data(), SIGNAL(customContextMenuRequested(QPoint
)), this, SLOT(contextMenuTriggered(QPoint
)));
252 m_filterInfoLabelIcon
->hide();
254 //Connect context menu
255 ui
->view_log
->setContextMenuPolicy(Qt::CustomContextMenu
);
256 connect(ui
->view_log
, SIGNAL(customContextMenuRequested(QPoint
)), this, SLOT(contextMenuTriggered(QPoint
)));
257 connect(contextMenuDetailsAction
, SIGNAL(triggered(bool)), this, SLOT(contextMenuDetailsActionTriggered()));
258 connect(contextMenuShowFileAction
, SIGNAL(triggered(bool)), this, SLOT(contextMenuShowFileActionTriggered()));
259 for(size_t i
= 0; i
< 5; i
++)
261 if(contextMenuFilterAction
[i
]) connect(contextMenuFilterAction
[i
], SIGNAL(triggered(bool)), this, SLOT(contextMenuFilterActionTriggered()));
263 SET_FONT_BOLD(contextMenuDetailsAction
, true);
265 //Setup file extensions
266 if(!m_settings
->renameFiles_fileExtension().isEmpty())
268 m_fileExts
.reset(new FileExtsModel());
269 m_fileExts
->importItems(m_settings
->renameFiles_fileExtension());
275 for(int i
= 0; i
< fileListModel
->rowCount(); i
++)
277 m_pendingJobs
.append(fileListModel
->getFile(fileListModel
->index(i
,0)));
282 ui
->label_headerStatus
->setText(QString("<b>%1</b><br>%2").arg(tr("Encoding Files"), tr("Your files are being encoded, please be patient...")));
284 //Enable system tray icon
285 connect(m_systemTray
.data(), SIGNAL(activated(QSystemTrayIcon::ActivationReason
)), this, SLOT(systemTrayActivated(QSystemTrayIcon::ActivationReason
)));
288 m_runningThreads
= 0;
291 m_succeededJobs
.clear();
292 m_failedJobs
.clear();
293 m_skippedJobs
.clear();
294 m_userAborted
= false;
295 m_forcedAbort
= false;
298 ////////////////////////////////////////////////////////////
300 ////////////////////////////////////////////////////////////
302 ProcessingDialog::~ProcessingDialog(void)
304 ui
->view_log
->setModel(NULL
);
306 if(!m_progressIndicator
.isNull())
308 m_progressIndicator
->stop();
311 if(!m_diskObserver
.isNull())
313 m_diskObserver
->stop();
314 if(!m_diskObserver
->wait(15000))
316 m_diskObserver
->terminate();
317 m_diskObserver
->wait();
321 if(!m_cpuObserver
.isNull())
323 m_cpuObserver
->stop();
324 if(!m_cpuObserver
->wait(15000))
326 m_cpuObserver
->terminate();
327 m_cpuObserver
->wait();
331 if(!m_ramObserver
.isNull())
333 m_ramObserver
->stop();
334 if(!m_ramObserver
->wait(15000))
336 m_ramObserver
->terminate();
337 m_ramObserver
->wait();
341 if(!m_threadPool
.isNull())
343 if(!m_threadPool
->waitForDone(100))
345 emit
abortRunningTasks();
346 m_threadPool
->waitForDone();
350 m_taskbar
->setOverlayIcon(NULL
);
351 m_taskbar
->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_NONE
);
356 ////////////////////////////////////////////////////////////
358 ////////////////////////////////////////////////////////////
360 void ProcessingDialog::showEvent(QShowEvent
*event
)
362 QDialog::showEvent(event
);
366 static const char *NA
= " N/A";
368 MUtils::GUI::enable_close_button(this, false);
369 ui
->button_closeDialog
->setEnabled(false);
370 ui
->button_AbortProcess
->setEnabled(false);
372 MUtils::OS::change_process_priority(1);
374 ui
->label_cpu
->setText(NA
);
375 ui
->label_disk
->setText(NA
);
376 ui
->label_ram
->setText(NA
);
378 QTimer::singleShot(500, this, SLOT(initEncoding()));
382 //Force update geometry
386 void ProcessingDialog::closeEvent(QCloseEvent
*event
)
388 if(!ui
->button_closeDialog
->isEnabled())
394 m_systemTray
->setVisible(false);
398 bool ProcessingDialog::eventFilter(QObject
*obj
, QEvent
*event
)
400 if(obj
== ui
->label_versionInfo
)
402 if(event
->type() == QEvent::Enter
)
404 QPalette palette
= ui
->label_versionInfo
->palette();
405 *m_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
, *m_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 MUtils::GUI::USER_EVENT_QUERYENDSESSION
:
430 qWarning("System is shutting down, preparing to abort...");
431 if(!m_userAborted
) abortEncoding(true);
433 case MUtils::GUI::USER_EVENT_ENDSESSION
:
434 qWarning("System is shutting down, encoding will be aborted now...");
439 if(!m_userAborted
) abortEncoding(true);
440 qApp
->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 ////////////////////////////////////////////////////////////
467 ////////////////////////////////////////////////////////////
469 void ProcessingDialog::initEncoding(void)
471 qDebug("Initializing encoding process...");
473 m_runningThreads
= 0;
476 m_succeededJobs
.clear();
477 m_failedJobs
.clear();
478 m_skippedJobs
.clear();
479 m_userAborted
= m_forcedAbort
= false;
481 m_progressIndicator
->start();
483 DecoderRegistry::configureDecoders(m_settings
);
485 CHANGE_BACKGROUND_COLOR(ui
->frame_header
, QColor(Qt::white
));
486 SET_PROGRESS_TEXT(tr("Encoding files, please wait..."));
488 ui
->button_closeDialog
->setEnabled(false);
489 ui
->button_AbortProcess
->setEnabled(true);
490 ui
->progressBar
->setRange(0, m_pendingJobs
.count());
491 ui
->checkBox_shutdownComputer
->setEnabled(true);
492 ui
->checkBox_shutdownComputer
->setChecked(false);
494 m_taskbar
->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_NORMAL
);
495 m_taskbar
->setTaskbarProgress(0, m_pendingJobs
.count());
496 m_taskbar
->setOverlayIcon(&QIcon(":/icons/control_play_blue.png"));
500 m_diskObserver
.reset(new DiskObserverThread(m_tempFolder
));
501 connect(m_diskObserver
.data(), SIGNAL(messageLogged(QString
,int)), m_progressModel
.data(), SLOT(addSystemMessage(QString
,int)), Qt::QueuedConnection
);
502 connect(m_diskObserver
.data(), SIGNAL(freeSpaceChanged(quint64
)), this, SLOT(diskUsageHasChanged(quint64
)), Qt::QueuedConnection
);
503 m_diskObserver
->start();
507 m_cpuObserver
.reset(new CPUObserverThread());
508 connect(m_cpuObserver
.data(), SIGNAL(currentUsageChanged(double)), this, SLOT(cpuUsageHasChanged(double)), Qt::QueuedConnection
);
509 m_cpuObserver
->start();
513 m_ramObserver
.reset(new RAMObserverThread());
514 connect(m_ramObserver
.data(), SIGNAL(currentUsageChanged(double)), this, SLOT(ramUsageHasChanged(double)), Qt::QueuedConnection
);
515 m_ramObserver
->start();
518 if(m_threadPool
.isNull())
520 m_threadPool
.reset(createThreadPool());
521 if (m_threadPool
->maxThreadCount() > 1)
523 m_progressModel
->addSystemMessage(tr("Multi-threading enabled: Running %1 instances in parallel!").arg(QString::number(m_threadPool
->maxThreadCount())));
527 m_initThreads
= m_threadPool
->maxThreadCount();
528 QTimer::singleShot(100, this, SLOT(initNextJob()));
530 m_totalTime
.reset(new QElapsedTimer());
531 m_totalTime
->start();
534 void ProcessingDialog::initNextJob(void)
536 if((m_initThreads
> 0) && (!m_userAborted
))
539 if(--m_initThreads
> 0)
541 QTimer::singleShot(32, this, SLOT(initNextJob()));
546 void ProcessingDialog::startNextJob(void)
548 if(m_pendingJobs
.isEmpty())
550 qWarning("No more files left, unable to start another job!");
558 AudioFileModel currentFile
= m_pendingJobs
.takeFirst();
559 updateMetaInfo(currentFile
);
561 //Create encoder instance
562 AbstractEncoder
*encoder
= EncoderRegistry::createInstance(m_settings
->compressionEncoder(), m_settings
);
564 //Create processing thread
565 QScopedPointer
<ProcessThread
> thread(new ProcessThread
568 (m_settings
->outputToSourceDir() ? QFileInfo(currentFile
.filePath()).absolutePath() : m_settings
->outputDir()),
571 m_settings
->prependRelativeSourcePath() && (!m_settings
->outputToSourceDir())
575 if(m_settings
->forceStereoDownmix())
577 thread
->addFilter(new DownmixFilter());
579 if(m_settings
->samplingRate() > 0)
581 const int targetRate
= SettingsModel::samplingRates
[qBound(1, m_settings
->samplingRate(), 6)];
582 if((targetRate
!= currentFile
.techInfo().audioSamplerate()) || (currentFile
.techInfo().audioSamplerate() == 0))
584 if (encoder
->toEncoderInfo()->isResamplingSupported())
586 encoder
->setSamplingRate(targetRate
);
590 thread
->addFilter(new ResampleFilter(targetRate
));
594 if((m_settings
->toneAdjustBass() != 0) || (m_settings
->toneAdjustTreble() != 0))
596 thread
->addFilter(new ToneAdjustFilter(m_settings
->toneAdjustBass(), m_settings
->toneAdjustTreble()));
598 if(m_settings
->normalizationFilterEnabled())
600 thread
->addFilter(new NormalizeFilter(m_settings
->normalizationFilterMaxVolume(), m_settings
->normalizationFilterDynamic(), m_settings
->normalizationFilterCoupled(), m_settings
->normalizationFilterSize()));
602 if(m_settings
->renameFiles_renameEnabled() && (!m_settings
->renameFiles_renamePattern().simplified().isEmpty()))
604 thread
->setRenamePattern(m_settings
->renameFiles_renamePattern());
606 if(m_settings
->renameFiles_regExpEnabled() && (!m_settings
->renameFiles_regExpSearch().trimmed().isEmpty()) && (!m_settings
->renameFiles_regExpReplace().simplified().isEmpty()))
608 thread
->setRenameRegExp(m_settings
->renameFiles_regExpSearch(), m_settings
->renameFiles_regExpReplace());
610 if(!m_fileExts
.isNull())
612 thread
->setRenameFileExt(m_fileExts
->apply(QString::fromUtf8(EncoderRegistry::getEncoderInfo(m_settings
->compressionEncoder())->extension())));
614 if(m_settings
->overwriteMode() != SettingsModel::Overwrite_KeepBoth
)
616 thread
->setOverwriteMode((m_settings
->overwriteMode() == SettingsModel::Overwrite_SkipFile
), (m_settings
->overwriteMode() == SettingsModel::Overwrite_Replaces
));
618 if (m_settings
->keepOriginalDataTime())
620 thread
->setKeepDateTime(m_settings
->keepOriginalDataTime());
624 m_allJobs
.append(thread
->getId());
626 //Connect thread signals
627 connect(thread
.data(), SIGNAL(processFinished()), this, SLOT(doneEncoding()), Qt::QueuedConnection
);
628 connect(thread
.data(), SIGNAL(processStateInitialized(QUuid
,QString
,QString
,int)), m_progressModel
.data(), SLOT(addJob(QUuid
,QString
,QString
,int)), Qt::QueuedConnection
);
629 connect(thread
.data(), SIGNAL(processStateChanged(QUuid
,QString
,int)), m_progressModel
.data(), SLOT(updateJob(QUuid
,QString
,int)), Qt::QueuedConnection
);
630 connect(thread
.data(), SIGNAL(processStateFinished(QUuid
,QString
,int)), this, SLOT(processFinished(QUuid
,QString
,int)), Qt::QueuedConnection
);
631 connect(thread
.data(), SIGNAL(processMessageLogged(QUuid
,QString
)), m_progressModel
.data(), SLOT(appendToLog(QUuid
,QString
)), Qt::QueuedConnection
);
632 connect(this, SIGNAL(abortRunningTasks()), thread
.data(), SLOT(abort()), Qt::DirectConnection
);
634 //Initialize thread object
637 qFatal("Fatal Error: Thread initialization has failed!");
641 if(!thread
->start(m_threadPool
.data()))
643 qWarning("Job failed to start or the file was skipped!");
647 thread
.take(); //will be auto-deleted by QThreadPool!
650 void ProcessingDialog::abortEncoding(bool force
)
652 m_userAborted
= true;
653 if(force
) m_forcedAbort
= true;
654 ui
->button_AbortProcess
->setEnabled(false);
655 SET_PROGRESS_TEXT(tr("Aborted! Waiting for running jobs to terminate..."));
656 emit
abortRunningTasks();
659 void ProcessingDialog::doneEncoding(void)
662 ui
->progressBar
->setValue(ui
->progressBar
->value() + 1);
666 SET_PROGRESS_TEXT(tr("Encoding: %n file(s) of %1 completed so far, please wait...", "", ui
->progressBar
->value()).arg(QString::number(ui
->progressBar
->maximum())));
667 m_taskbar
->setTaskbarProgress(ui
->progressBar
->value(), ui
->progressBar
->maximum());
670 if((!m_pendingJobs
.isEmpty()) && (!m_userAborted
))
672 QTimer::singleShot(0, this, SLOT(startNextJob()));
673 qDebug("%d files left, starting next job...", m_pendingJobs
.count());
677 if(m_runningThreads
> 0)
679 qDebug("No files left, but still have %u running jobs.", m_runningThreads
);
683 QApplication::setOverrideCursor(Qt::WaitCursor
);
684 qDebug("Running jobs: %u", m_runningThreads
);
686 if(!m_userAborted
&& m_settings
->createPlaylist() && !m_settings
->outputToSourceDir())
688 SET_PROGRESS_TEXT(tr("Creating the playlist file, please wait..."));
689 qApp
->processEvents(QEventLoop::ExcludeUserInputEvents
);
695 CHANGE_BACKGROUND_COLOR(ui
->frame_header
, QColor("#FFFFE0"));
696 m_taskbar
->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_ERROR
);
697 m_taskbar
->setOverlayIcon(&QIcon(":/icons/error.png"));
698 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!"));
699 m_systemTray
->showMessage(tr("LameXP - Aborted"), tr("Process was aborted by the user."), QSystemTrayIcon::Warning
);
700 m_systemTray
->setIcon(QIcon(":/icons/cd_delete.png"));
701 qApp
->processEvents(QEventLoop::ExcludeUserInputEvents
);
702 if(!m_forcedAbort
) PLAY_SOUND_OPTIONAL("aborted", false);
706 if((!m_totalTime
.isNull()) && m_totalTime
->isValid())
708 m_progressModel
->addSystemMessage(tr("Process finished after %1.").arg(time2text(m_totalTime
->elapsed())), ProgressModel::SysMsg_Performance
);
709 m_totalTime
->invalidate();
712 if(m_failedJobs
.count() > 0)
714 CHANGE_BACKGROUND_COLOR(ui
->frame_header
, QColor("#FFF0F0"));
715 m_taskbar
->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_ERROR
);
716 m_taskbar
->setOverlayIcon(&QIcon(":/icons/exclamation.png"));
717 if(m_skippedJobs
.count() > 0)
719 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())));
723 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())));
725 m_systemTray
->showMessage(tr("LameXP - Error"), tr("At least one file has failed!"), QSystemTrayIcon::Critical
);
726 m_systemTray
->setIcon(QIcon(":/icons/cd_delete.png"));
727 qApp
->processEvents(QEventLoop::ExcludeUserInputEvents
);
728 PLAY_SOUND_OPTIONAL("error", false);
732 CHANGE_BACKGROUND_COLOR(ui
->frame_header
, QColor("#F0FFF0"));
733 m_taskbar
->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_NORMAL
);
734 m_taskbar
->setOverlayIcon(&QIcon(":/icons/accept.png"));
735 if(m_skippedJobs
.count() > 0)
737 SET_PROGRESS_TEXT(tr("All files completed successfully. Skipped %n file(s).", "", m_skippedJobs
.count()));
741 SET_PROGRESS_TEXT(tr("All files completed successfully."));
743 m_systemTray
->showMessage(tr("LameXP - Done"), tr("All files completed successfully."), QSystemTrayIcon::Information
);
744 m_systemTray
->setIcon(QIcon(":/icons/cd_add.png"));
745 qApp
->processEvents(QEventLoop::ExcludeUserInputEvents
);
746 PLAY_SOUND_OPTIONAL("success", false);
750 MUtils::GUI::enable_close_button(this, true);
751 ui
->button_closeDialog
->setEnabled(true);
752 ui
->button_AbortProcess
->setEnabled(false);
753 ui
->checkBox_shutdownComputer
->setEnabled(false);
755 m_progressModel
->restoreHiddenItems();
756 ui
->view_log
->scrollToBottom();
757 m_progressIndicator
->stop();
758 ui
->progressBar
->setValue(ui
->progressBar
->maximum());
759 m_taskbar
->setTaskbarProgress(ui
->progressBar
->value(), ui
->progressBar
->maximum());
761 QApplication::restoreOverrideCursor();
763 if(!m_userAborted
&& ui
->checkBox_shutdownComputer
->isChecked())
765 if(shutdownComputer())
767 m_shutdownFlag
= m_settings
->hibernateComputer() ? SHUTDOWN_FLAG_HIBERNATE
: SHUTDOWN_FLAG_POWER_OFF
;
773 void ProcessingDialog::processFinished(const QUuid
&jobId
, const QString
&outFileName
, int success
)
777 m_playList
.insert(jobId
, outFileName
);
778 m_succeededJobs
.append(jobId
);
782 m_playList
.insert(jobId
, outFileName
);
783 m_skippedJobs
.append(jobId
);
787 m_failedJobs
.append(jobId
);
790 //Update filter as soon as a job finished!
791 if(m_progressViewFilter
>= 0)
793 QTimer::singleShot(0, this, SLOT(progressViewFilterChanged()));
797 void ProcessingDialog::progressModelChanged(void)
799 //Update filter as soon as the model changes!
800 if(m_progressViewFilter
>= 0)
802 QTimer::singleShot(0, this, SLOT(progressViewFilterChanged()));
805 QTimer::singleShot(0, ui
->view_log
, SLOT(scrollToBottom()));
808 void ProcessingDialog::logViewDoubleClicked(const QModelIndex
&index
)
810 if(m_runningThreads
== 0)
812 const QStringList
&logFile
= m_progressModel
->getLogFile(index
);
814 if(!logFile
.isEmpty())
816 LogViewDialog
*logView
= new LogViewDialog(this);
817 logView
->setWindowTitle(QString("LameXP - [%1]").arg(m_progressModel
->data(index
, Qt::DisplayRole
).toString()));
818 logView
->exec(logFile
);
819 MUTILS_DELETE(logView
);
823 QMessageBox::information(this, windowTitle(), m_progressModel
->data(m_progressModel
->index(index
.row(), 0)).toString());
828 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN
);
832 void ProcessingDialog::logViewSectionSizeChanged(int logicalIndex
, int oldSize
, int newSize
)
834 if(logicalIndex
== 1)
836 if(QHeaderView
*hdr
= ui
->view_log
->horizontalHeader())
838 hdr
->setMinimumSectionSize(qMax(hdr
->minimumSectionSize(), hdr
->sectionSize(1)));
843 void ProcessingDialog::contextMenuTriggered(const QPoint
&pos
)
845 QAbstractScrollArea
*scrollArea
= dynamic_cast<QAbstractScrollArea
*>(QObject::sender());
846 QWidget
*sender
= scrollArea
? scrollArea
->viewport() : dynamic_cast<QWidget
*>(QObject::sender());
848 if(pos
.x() <= sender
->width() && pos
.y() <= sender
->height() && pos
.x() >= 0 && pos
.y() >= 0)
850 m_contextMenu
->popup(sender
->mapToGlobal(pos
));
854 void ProcessingDialog::contextMenuDetailsActionTriggered(void)
856 QModelIndex index
= ui
->view_log
->indexAt(ui
->view_log
->viewport()->mapFromGlobal(m_contextMenu
->pos()));
857 logViewDoubleClicked(index
.isValid() ? index
: ui
->view_log
->currentIndex());
860 void ProcessingDialog::contextMenuShowFileActionTriggered(void)
862 QModelIndex index
= ui
->view_log
->indexAt(ui
->view_log
->viewport()->mapFromGlobal(m_contextMenu
->pos()));
863 const QUuid
&jobId
= m_progressModel
->getJobId(index
.isValid() ? index
: ui
->view_log
->currentIndex());
864 QString filePath
= m_playList
.value(jobId
, QString());
866 if(filePath
.isEmpty())
868 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN
);
872 if(QFileInfo(filePath
).exists())
874 QString systemRootPath
;
876 QDir
systemRoot(MUtils::OS::known_folder(MUtils::OS::FOLDER_SYSTEMFOLDER
));
877 if(systemRoot
.exists() && systemRoot
.cdUp())
879 systemRootPath
= systemRoot
.canonicalPath();
882 if(!systemRootPath
.isEmpty())
884 QFileInfo
explorer(QString("%1/explorer.exe").arg(systemRootPath
));
885 if(explorer
.exists() && explorer
.isFile())
887 QProcess::execute(explorer
.canonicalFilePath(), QStringList() << "/select," << QDir::toNativeSeparators(QFileInfo(filePath
).canonicalFilePath()));
893 qWarning("SystemRoot directory could not be detected!");
898 qWarning("File not found: %s", filePath
.toLatin1().constData());
899 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR
);
903 void ProcessingDialog::contextMenuFilterActionTriggered(void)
905 if(QAction
*action
= dynamic_cast<QAction
*>(QObject::sender()))
907 if(action
->data().type() == QVariant::Int
)
909 m_progressViewFilter
= action
->data().toInt();
910 progressViewFilterChanged();
911 QTimer::singleShot(0, this, SLOT(progressViewFilterChanged()));
912 QTimer::singleShot(0, ui
->view_log
, SLOT(scrollToBottom()));
913 action
->setChecked(true);
919 * Filter progress items
921 void ProcessingDialog::progressViewFilterChanged(void)
923 bool matchFound
= false;
925 for(int i
= 0; i
< ui
->view_log
->model()->rowCount(); i
++)
927 QModelIndex index
= (m_progressViewFilter
>= 0) ? m_progressModel
->index(i
, 0) : QModelIndex();
928 const bool bHide
= index
.isValid() ? (m_progressModel
->getJobState(index
) != m_progressViewFilter
) : false;
929 ui
->view_log
->setRowHidden(i
, bHide
); matchFound
= matchFound
|| (!bHide
);
932 if((m_progressViewFilter
>= 0) && (!matchFound
))
934 if(m_filterInfoLabel
->isHidden() || (dynamic_cast<IntUserData
*>(m_filterInfoLabel
->userData(0))->value() != m_progressViewFilter
))
936 dynamic_cast<IntUserData
*>(m_filterInfoLabel
->userData(0))->setValue(m_progressViewFilter
);
937 m_filterInfoLabel
->setText(QString("<p>» %1 «</p>").arg(tr("None of the items matches the current filtering rules")));
938 m_filterInfoLabel
->show();
939 m_filterInfoLabelIcon
->setPixmap(m_progressModel
->getIcon(static_cast<ProgressModel::JobState
>(m_progressViewFilter
)).pixmap(16, 16, QIcon::Disabled
));
940 m_filterInfoLabelIcon
->show();
944 else if(!m_filterInfoLabel
->isHidden())
946 m_filterInfoLabel
->hide();
947 m_filterInfoLabelIcon
->hide();
951 ////////////////////////////////////////////////////////////
953 ////////////////////////////////////////////////////////////
955 QThreadPool
*ProcessingDialog::createThreadPool(void)
957 quint32 maximumInstances
= qBound(0U, m_settings
->maximumInstances(), MAX_INSTANCES
);
958 if (maximumInstances
< 1U)
960 const MUtils::CPUFetaures::cpu_info_t cpuFeatures
= MUtils::CPUFetaures::detect();
961 const quint32 nProcessors
= qBound(1U, cpuFeatures
.count
, MAX_INSTANCES
);
962 maximumInstances
= isFastSeekingDevice(m_tempFolder
) ? nProcessors
: cores2instances(nProcessors
);
964 QThreadPool
*const threadPool
= new QThreadPool();
965 threadPool
->setMaxThreadCount(qBound(1U, maximumInstances
, static_cast<unsigned int>(m_pendingJobs
.count())));
969 void ProcessingDialog::writePlayList(void)
971 if(m_succeededJobs
.count() <= 0 || m_allJobs
.count() <= 0)
973 qWarning("WritePlayList: Nothing to do!");
977 //Init local variables
979 QRegExp
regExp1("\\[\\d\\d\\][^/\\\\]+$", Qt::CaseInsensitive
);
980 QRegExp
regExp2("\\(\\d\\d\\)[^/\\\\]+$", Qt::CaseInsensitive
);
981 QRegExp
regExp3("\\d\\d[^/\\\\]+$", Qt::CaseInsensitive
);
982 bool usePrefix
[3] = {true, true, true};
983 bool useUtf8
= false;
986 //Generate playlist name
987 QString playListName
= (m_metaInfo
->album().isEmpty() ? "Playlist" : m_metaInfo
->album());
988 if(!m_metaInfo
->artist().isEmpty())
990 playListName
= QString("%1 - %2").arg(m_metaInfo
->artist(), playListName
);
993 //Clean playlist name
994 playListName
= MUtils::clean_file_name(playListName
, true);
996 //Create list of audio files
997 for(int i
= 0; i
< m_allJobs
.count(); i
++)
999 if(!m_succeededJobs
.contains(m_allJobs
.at(i
))) continue;
1000 list
<< QDir::toNativeSeparators(QDir(m_settings
->outputDir()).relativeFilePath(m_playList
.value(m_allJobs
.at(i
), "N/A")));
1004 for(int i
= 0; i
< list
.count(); i
++)
1006 if(regExp1
.indexIn(list
.at(i
)) < 0) usePrefix
[0] = false;
1007 if(regExp2
.indexIn(list
.at(i
)) < 0) usePrefix
[1] = false;
1008 if(regExp3
.indexIn(list
.at(i
)) < 0) usePrefix
[2] = false;
1010 if(usePrefix
[0] || usePrefix
[1] || usePrefix
[2])
1012 playListName
.prepend(usePrefix
[0] ? "[00] " : (usePrefix
[1] ? "(00) " : "00 "));
1015 //Do we need an UTF-8 playlist?
1016 for(int i
= 0; i
< list
.count(); i
++)
1018 if(wcscmp(MUTILS_WCHR(QString::fromLatin1(list
.at(i
).toLatin1().constData())), MUTILS_WCHR(list
.at(i
))))
1025 //Generate playlist output file
1026 QString playListFile
= QString("%1/%2.%3").arg(m_settings
->outputDir(), playListName
, (useUtf8
? "m3u8" : "m3u"));
1027 while(QFileInfo(playListFile
).exists())
1029 playListFile
= QString("%1/%2 (%3).%4").arg(m_settings
->outputDir(), playListName
, QString::number(++counter
), (useUtf8
? "m3u8" : "m3u"));
1032 //Now write playlist to output file
1033 QFile
playList(playListFile
);
1034 if(playList
.open(QIODevice::WriteOnly
))
1038 playList
.write("\xef\xbb\xbf");
1040 playList
.write("#EXTM3U\r\n");
1041 while(!list
.isEmpty())
1043 playList
.write(useUtf8
? MUTILS_UTF8(list
.takeFirst()) : list
.takeFirst().toLatin1().constData());
1044 playList
.write("\r\n");
1050 QMessageBox::warning(this, tr("Playlist creation failed"), QString("%1<br><nobr>%2</nobr>").arg(tr("The playlist file could not be created:"), playListFile
));
1054 void ProcessingDialog::updateMetaInfo(AudioFileModel
&audioFile
)
1056 if(!m_settings
->writeMetaTags())
1058 audioFile
.metaInfo().reset();
1062 audioFile
.metaInfo().update(*m_metaInfo
, true);
1064 if(audioFile
.metaInfo().position() == UINT_MAX
)
1066 audioFile
.metaInfo().setPosition(m_currentFile
);
1070 void ProcessingDialog::systemTrayActivated(QSystemTrayIcon::ActivationReason reason
)
1072 if(reason
== QSystemTrayIcon::DoubleClick
)
1074 MUtils::GUI::bring_to_front(this);
1078 void ProcessingDialog::cpuUsageHasChanged(const double val
)
1081 ui
->label_cpu
->setText(QString().sprintf(" %d%%", qRound(val
* 100.0)));
1082 UPDATE_MIN_WIDTH(ui
->label_cpu
);
1085 void ProcessingDialog::ramUsageHasChanged(const double val
)
1088 ui
->label_ram
->setText(QString().sprintf(" %d%%", qRound(val
* 100.0)));
1089 UPDATE_MIN_WIDTH(ui
->label_ram
);
1092 void ProcessingDialog::diskUsageHasChanged(const quint64 val
)
1095 const char *postfixStr
[6] = {"B", "KB", "MB", "GB", "TB", "PB"};
1096 double space
= static_cast<double>(val
);
1098 while((space
>= 1000.0) && (postfix
< 5))
1100 space
= space
/ 1024.0;
1104 ui
->label_disk
->setText(QString().sprintf(" %3.1f %s", space
, postfixStr
[postfix
]));
1105 UPDATE_MIN_WIDTH(ui
->label_disk
);
1108 bool ProcessingDialog::shutdownComputer(void)
1110 const int iTimeout
= m_settings
->hibernateComputer() ? 10 : 30;
1111 const Qt::WindowFlags flags
= Qt::WindowStaysOnTopHint
| Qt::CustomizeWindowHint
| Qt::WindowTitleHint
| Qt::MSWindowsFixedSizeDialogHint
| Qt::WindowSystemMenuHint
;
1112 const QString text
= QString("%1%2%1").arg(QString().fill(' ', 18), tr("Warning: Computer will shutdown in %1 seconds..."));
1114 qWarning("Initiating shutdown sequence!");
1116 QProgressDialog
progressDialog(text
.arg(iTimeout
), tr("Cancel Shutdown"), 0, iTimeout
+ 1, this, flags
);
1117 QPushButton
*cancelButton
= new QPushButton(tr("Cancel Shutdown"), &progressDialog
);
1118 cancelButton
->setIcon(QIcon(":/icons/power_on.png"));
1119 progressDialog
.setModal(true);
1120 progressDialog
.setAutoClose(false);
1121 progressDialog
.setAutoReset(false);
1122 progressDialog
.setWindowIcon(QIcon(":/icons/power_off.png"));
1123 progressDialog
.setCancelButton(cancelButton
);
1124 progressDialog
.show();
1126 qApp
->processEvents(QEventLoop::ExcludeUserInputEvents
);
1128 QApplication::setOverrideCursor(Qt::WaitCursor
);
1129 PLAY_SOUND_OPTIONAL("shutdown", false);
1130 QApplication::restoreOverrideCursor();
1133 timer
.setInterval(1000);
1136 QEventLoop
eventLoop(this);
1137 connect(&timer
, SIGNAL(timeout()), &eventLoop
, SLOT(quit()));
1138 connect(&progressDialog
, SIGNAL(canceled()), &eventLoop
, SLOT(quit()));
1140 for(int i
= 1; i
<= iTimeout
; i
++)
1143 if(progressDialog
.wasCanceled())
1145 progressDialog
.close();
1148 progressDialog
.setValue(i
+1);
1149 progressDialog
.setLabelText(text
.arg(iTimeout
-i
));
1150 if(iTimeout
-i
== 3) progressDialog
.setCancelButton(NULL
);
1151 qApp
->processEvents(QEventLoop::ExcludeUserInputEvents
);
1152 PLAY_SOUND_OPTIONAL(((i
< iTimeout
) ? "beep" : "beep2"), false);
1155 progressDialog
.close();
1159 ////////////////////////////////////////////////////////////
1161 ////////////////////////////////////////////////////////////
1163 bool ProcessingDialog::isFastSeekingDevice(const QString
&path
)
1165 bool haveFastSeeking
;
1166 if (MUtils::OS::get_drive_type(path
, &haveFastSeeking
) != MUtils::OS::DRIVE_TYPE_ERR
)
1168 return haveFastSeeking
;
1173 quint32
ProcessingDialog::cores2instances(const quint32
&cores
)
1175 //This function is a "cubic spline" with sampling points at:
1176 //(1,1); (2,2); (4,4); (8,6); (16,8); (32,11); (64,16)
1177 static const double LUT
[8][5] =
1179 { 1.0, 0.014353554, -0.043060662, 1.028707108, 0.000000000},
1180 { 2.0, -0.028707108, 0.215303309, 0.511979167, 0.344485294},
1181 { 4.0, 0.010016468, -0.249379596, 2.370710784, -2.133823529},
1182 { 8.0, 0.000282437, -0.015762868, 0.501776961, 2.850000000},
1183 {16.0, 0.000033270, -0.003802849, 0.310416667, 3.870588235},
1184 {32.0, 0.000006343, -0.001217831, 0.227696078, 4.752941176},
1185 {64.0, 0.000000000, 0.000000000, 0.000000000, 16.000000000},
1186 {DBL_MAX
, 0.0, 0.0, 0.0, 0.0}
1189 double x
= abs(static_cast<double>(cores
)), y
= 1.0;
1191 for(size_t i
= 0; i
< 7; i
++)
1193 if((x
>= LUT
[i
][0]) && (x
< LUT
[i
+1][0]))
1195 y
= (((((LUT
[i
][1] * x
) + LUT
[i
][2]) * x
) + LUT
[i
][3]) * x
) + LUT
[i
][4];
1200 return static_cast<quint32
>(qRound(y
));
1203 QString
ProcessingDialog::time2text(const qint64
&msec
)
1205 const qint64 MILLISECONDS_PER_DAY
= 86399999; //24x60x60x1000 - 1
1206 const QTime time
= QTime().addMSecs(qMin(msec
, MILLISECONDS_PER_DAY
));
1210 if (time
.hour() > 0)
1212 a
= tr("%n hour(s)", "", time
.hour());
1213 b
= tr("%n minute(s)", "", time
.minute());
1215 else if (time
.minute() > 0)
1217 a
= tr("%n minute(s)", "", time
.minute());
1218 b
= tr("%n second(s)", "", time
.second());
1222 a
= tr("%n second(s)", "", time
.second());
1223 b
= tr("%n millisecond(s)", "", time
.msec());
1226 return QString("%1, %2").arg(a
, b
);