1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2015 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"
46 #include <MUtils/Global.h>
47 #include <MUtils/OSSupport.h>
48 #include <MUtils/GUI.h>
49 #include <MUtils/CPUFeatures.h>
50 #include <MUtils/Sound.h>
51 #include <MUtils/Taskbar7.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>
72 #include <QElapsedTimer>
73 #include <QThreadPool>
79 ////////////////////////////////////////////////////////////
81 //Maximum number of parallel instances
82 #define MAX_INSTANCES 32U
84 //Function to calculate the number of instances
85 static int cores2instances(int cores
);
87 ////////////////////////////////////////////////////////////
89 #define CHANGE_BACKGROUND_COLOR(WIDGET, COLOR) do \
91 QPalette palette = WIDGET->palette(); \
92 palette.setColor(QPalette::Background, COLOR); \
93 WIDGET->setPalette(palette); \
97 #define SET_PROGRESS_TEXT(TXT) do \
99 ui->label_progress->setText(TXT); \
100 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
*fileListModel
, const AudioFileModel_MetaInfo
*metaInfo
, SettingsModel
*settings
, QWidget
*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
),
161 m_diskObserver(NULL
),
164 m_progressViewFilter(-1),
166 m_defaultColor(new QColor()),
169 //Init the dialog, from the .ui file
171 setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint
);
173 //Update the window icon
174 MUtils::GUI::set_window_icon(this, lamexp_app_icon(), true);
177 ui
->label_headerIcon
->setPixmap(lamexp_app_icon().pixmap(ui
->label_headerIcon
->size()));
180 ui
->label_versionInfo
->setText(QString().sprintf("v%d.%02d %s (Build %d)", lamexp_version_major(), lamexp_version_minor(), lamexp_version_release(), lamexp_version_build()));
181 ui
->label_versionInfo
->installEventFilter(this);
184 qRegisterMetaType
<QUuid
>("QUuid");
186 //Center window in screen
187 QRect desktopRect
= QApplication::desktop()->screenGeometry();
188 QRect thisRect
= this->geometry();
189 move((desktopRect
.width() - thisRect
.width()) / 2, (desktopRect
.height() - thisRect
.height()) / 2);
190 setMinimumSize(thisRect
.width(), thisRect
.height());
193 connect(ui
->button_AbortProcess
, SIGNAL(clicked()), this, SLOT(abortEncoding()));
195 //Init progress indicator
196 m_progressIndicator
= new QMovie(":/images/Working.gif");
197 m_progressIndicator
->setCacheMode(QMovie::CacheAll
);
198 ui
->label_headerWorking
->setMovie(m_progressIndicator
);
199 ui
->progressBar
->setValue(0);
201 //Init progress model
202 m_progressModel
= new ProgressModel();
203 ui
->view_log
->setModel(m_progressModel
);
204 ui
->view_log
->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents
);
205 ui
->view_log
->verticalHeader()->hide();
206 ui
->view_log
->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents
);
207 ui
->view_log
->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch
);
208 ui
->view_log
->viewport()->installEventFilter(this);
209 connect(m_progressModel
, SIGNAL(rowsInserted(QModelIndex
,int,int)), this, SLOT(progressModelChanged()));
210 connect(m_progressModel
, SIGNAL(rowsMoved(QModelIndex
,int,int,QModelIndex
,int)), this, SLOT(progressModelChanged()));
211 connect(m_progressModel
, SIGNAL(rowsRemoved(QModelIndex
,int,int)), this, SLOT(progressModelChanged()));
212 connect(m_progressModel
, SIGNAL(modelReset()), this, SLOT(progressModelChanged()));
213 connect(ui
->view_log
, SIGNAL(activated(QModelIndex
)), this, SLOT(logViewDoubleClicked(QModelIndex
)));
214 connect(ui
->view_log
->horizontalHeader(), SIGNAL(sectionResized(int,int,int)), this, SLOT(logViewSectionSizeChanged(int,int,int)));
216 //Create context menu
217 m_contextMenu
= new QMenu();
218 QAction
*contextMenuDetailsAction
= m_contextMenu
->addAction(QIcon(":/icons/zoom.png"), tr("Show details for selected job"));
219 QAction
*contextMenuShowFileAction
= m_contextMenu
->addAction(QIcon(":/icons/folder_go.png"), tr("Browse Output File Location"));
220 m_contextMenu
->addSeparator();
222 //Create "filter" context menu
223 m_progressViewFilterGroup
= new QActionGroup(this);
224 QAction
*contextMenuFilterAction
[5] = {NULL
, NULL
, NULL
, NULL
, NULL
};
225 if(QMenu
*filterMenu
= m_contextMenu
->addMenu(QIcon(":/icons/filter.png"), tr("Filter Log Items")))
227 contextMenuFilterAction
[0] = filterMenu
->addAction(m_progressModel
->getIcon(ProgressModel::JobRunning
), tr("Show Running Only"));
228 contextMenuFilterAction
[1] = filterMenu
->addAction(m_progressModel
->getIcon(ProgressModel::JobComplete
), tr("Show Succeeded Only"));
229 contextMenuFilterAction
[2] = filterMenu
->addAction(m_progressModel
->getIcon(ProgressModel::JobFailed
), tr("Show Failed Only"));
230 contextMenuFilterAction
[3] = filterMenu
->addAction(m_progressModel
->getIcon(ProgressModel::JobSkipped
), tr("Show Skipped Only"));
231 contextMenuFilterAction
[4] = filterMenu
->addAction(m_progressModel
->getIcon(ProgressModel::JobState(-1)), tr("Show All Items"));
232 if(QAction
*act
= contextMenuFilterAction
[0]) { m_progressViewFilterGroup
->addAction(act
); act
->setCheckable(true); act
->setData(ProgressModel::JobRunning
); }
233 if(QAction
*act
= contextMenuFilterAction
[1]) { m_progressViewFilterGroup
->addAction(act
); act
->setCheckable(true); act
->setData(ProgressModel::JobComplete
); }
234 if(QAction
*act
= contextMenuFilterAction
[2]) { m_progressViewFilterGroup
->addAction(act
); act
->setCheckable(true); act
->setData(ProgressModel::JobFailed
); }
235 if(QAction
*act
= contextMenuFilterAction
[3]) { m_progressViewFilterGroup
->addAction(act
); act
->setCheckable(true); act
->setData(ProgressModel::JobSkipped
); }
236 if(QAction
*act
= contextMenuFilterAction
[4]) { m_progressViewFilterGroup
->addAction(act
); act
->setCheckable(true); act
->setData(-1); act
->setChecked(true); }
240 if(m_filterInfoLabel
= new QLabel(ui
->view_log
))
242 m_filterInfoLabel
->setFrameShape(QFrame::NoFrame
);
243 m_filterInfoLabel
->setAlignment(Qt::AlignHCenter
| Qt::AlignVCenter
);
244 m_filterInfoLabel
->setUserData(0, new IntUserData(-1));
245 SET_FONT_BOLD(m_filterInfoLabel
, true);
246 SET_TEXT_COLOR(m_filterInfoLabel
, Qt::darkGray
);
247 m_filterInfoLabel
->setContextMenuPolicy(Qt::CustomContextMenu
);
248 connect(m_filterInfoLabel
, SIGNAL(customContextMenuRequested(QPoint
)), this, SLOT(contextMenuTriggered(QPoint
)));
249 m_filterInfoLabel
->hide();
251 if(m_filterInfoLabelIcon
= new QLabel(ui
->view_log
))
253 m_filterInfoLabelIcon
->setFrameShape(QFrame::NoFrame
);
254 m_filterInfoLabelIcon
->setAlignment(Qt::AlignHCenter
| Qt::AlignTop
);
255 m_filterInfoLabelIcon
->setContextMenuPolicy(Qt::CustomContextMenu
);
256 const QIcon
&ico
= m_progressModel
->getIcon(ProgressModel::JobState(-1));
257 m_filterInfoLabelIcon
->setPixmap(ico
.pixmap(16, 16));
258 connect(m_filterInfoLabelIcon
, SIGNAL(customContextMenuRequested(QPoint
)), this, SLOT(contextMenuTriggered(QPoint
)));
259 m_filterInfoLabelIcon
->hide();
262 //Connect context menu
263 ui
->view_log
->setContextMenuPolicy(Qt::CustomContextMenu
);
264 connect(ui
->view_log
, SIGNAL(customContextMenuRequested(QPoint
)), this, SLOT(contextMenuTriggered(QPoint
)));
265 connect(contextMenuDetailsAction
, SIGNAL(triggered(bool)), this, SLOT(contextMenuDetailsActionTriggered()));
266 connect(contextMenuShowFileAction
, SIGNAL(triggered(bool)), this, SLOT(contextMenuShowFileActionTriggered()));
267 for(size_t i
= 0; i
< 5; i
++)
269 if(contextMenuFilterAction
[i
]) connect(contextMenuFilterAction
[i
], SIGNAL(triggered(bool)), this, SLOT(contextMenuFilterActionTriggered()));
271 SET_FONT_BOLD(contextMenuDetailsAction
, true);
276 for(int i
= 0; i
< fileListModel
->rowCount(); i
++)
278 m_pendingJobs
.append(fileListModel
->getFile(fileListModel
->index(i
,0)));
283 ui
->label_headerStatus
->setText(QString("<b>%1</b><br>%2").arg(tr("Encoding Files"), tr("Your files are being encoded, please be patient...")));
285 //Enable system tray icon
286 connect(m_systemTray
, SIGNAL(activated(QSystemTrayIcon::ActivationReason
)), this, SLOT(systemTrayActivated(QSystemTrayIcon::ActivationReason
)));
289 m_runningThreads
= 0;
292 m_succeededJobs
.clear();
293 m_failedJobs
.clear();
294 m_skippedJobs
.clear();
295 m_userAborted
= false;
296 m_forcedAbort
= false;
299 ////////////////////////////////////////////////////////////
301 ////////////////////////////////////////////////////////////
303 ProcessingDialog::~ProcessingDialog(void)
305 ui
->view_log
->setModel(NULL
);
307 if(m_progressIndicator
)
309 m_progressIndicator
->stop();
314 m_diskObserver
->stop();
315 if(!m_diskObserver
->wait(15000))
317 m_diskObserver
->terminate();
318 m_diskObserver
->wait();
324 m_cpuObserver
->stop();
325 if(!m_cpuObserver
->wait(15000))
327 m_cpuObserver
->terminate();
328 m_cpuObserver
->wait();
334 m_ramObserver
->stop();
335 if(!m_ramObserver
->wait(15000))
337 m_ramObserver
->terminate();
338 m_ramObserver
->wait();
344 if(!m_threadPool
->waitForDone(100))
346 emit
abortRunningTasks();
347 m_threadPool
->waitForDone();
351 MUTILS_DELETE(m_progressIndicator
);
352 MUTILS_DELETE(m_systemTray
);
353 MUTILS_DELETE(m_diskObserver
);
354 MUTILS_DELETE(m_cpuObserver
);
355 MUTILS_DELETE(m_ramObserver
);
356 MUTILS_DELETE(m_progressViewFilterGroup
);
357 MUTILS_DELETE(m_filterInfoLabel
);
358 MUTILS_DELETE(m_filterInfoLabelIcon
);
359 MUTILS_DELETE(m_contextMenu
);
360 MUTILS_DELETE(m_progressModel
);
361 MUTILS_DELETE(m_threadPool
);
362 MUTILS_DELETE(m_defaultColor
);
364 m_taskbar
->setOverlayIcon(NULL
);
365 m_taskbar
->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_NONE
);
370 ////////////////////////////////////////////////////////////
372 ////////////////////////////////////////////////////////////
374 void ProcessingDialog::showEvent(QShowEvent
*event
)
376 QDialog::showEvent(event
);
380 static const char *NA
= " N/A";
382 MUtils::GUI::enable_close_button(this, false);
383 ui
->button_closeDialog
->setEnabled(false);
384 ui
->button_AbortProcess
->setEnabled(false);
385 m_progressIndicator
->start();
386 m_systemTray
->setVisible(true);
388 MUtils::OS::change_process_priority(1);
390 ui
->label_cpu
->setText(NA
);
391 ui
->label_disk
->setText(NA
);
392 ui
->label_ram
->setText(NA
);
394 QTimer::singleShot(500, this, SLOT(initEncoding()));
398 //Force update geometry
402 void ProcessingDialog::closeEvent(QCloseEvent
*event
)
404 if(!ui
->button_closeDialog
->isEnabled())
410 m_systemTray
->setVisible(false);
414 bool ProcessingDialog::eventFilter(QObject
*obj
, QEvent
*event
)
416 if(obj
== ui
->label_versionInfo
)
418 if(event
->type() == QEvent::Enter
)
420 QPalette palette
= ui
->label_versionInfo
->palette();
421 *m_defaultColor
= palette
.color(QPalette::Normal
, QPalette::WindowText
);
422 palette
.setColor(QPalette::Normal
, QPalette::WindowText
, Qt::red
);
423 ui
->label_versionInfo
->setPalette(palette
);
425 else if(event
->type() == QEvent::Leave
)
427 QPalette palette
= ui
->label_versionInfo
->palette();
428 palette
.setColor(QPalette::Normal
, QPalette::WindowText
, *m_defaultColor
);
429 ui
->label_versionInfo
->setPalette(palette
);
431 else if(event
->type() == QEvent::MouseButtonPress
)
433 QUrl
url(lamexp_website_url());
434 QDesktopServices::openUrl(url
);
441 bool ProcessingDialog::event(QEvent
*e
)
445 case MUtils::GUI::USER_EVENT_QUERYENDSESSION
:
446 qWarning("System is shutting down, preparing to abort...");
447 if(!m_userAborted
) abortEncoding(true);
449 case MUtils::GUI::USER_EVENT_ENDSESSION
:
450 qWarning("System is shutting down, encoding will be aborted now...");
455 if(!m_userAborted
) abortEncoding(true);
456 qApp
->processEvents(QEventLoop::WaitForMoreEvents
| QEventLoop::ExcludeUserInputEvents
);
459 m_pendingJobs
.clear();
462 return QDialog::event(e
);
469 void ProcessingDialog::resizeEvent(QResizeEvent
*event
)
471 if(event
) QDialog::resizeEvent(event
);
473 if(QWidget
*port
= ui
->view_log
->viewport())
475 QRect geom
= port
->geometry();
476 m_filterInfoLabel
->setGeometry(geom
.left() + 16, geom
.top() + 16, geom
.width() - 32, 48);
477 m_filterInfoLabelIcon
->setGeometry(geom
.left() + 16, geom
.top() + 64, geom
.width() - 32, geom
.height() - 80);
481 ////////////////////////////////////////////////////////////
483 ////////////////////////////////////////////////////////////
485 void ProcessingDialog::initEncoding(void)
487 qDebug("Initializing encoding process...");
489 m_runningThreads
= 0;
492 m_succeededJobs
.clear();
493 m_failedJobs
.clear();
494 m_skippedJobs
.clear();
495 m_userAborted
= false;
496 m_forcedAbort
= false;
499 DecoderRegistry::configureDecoders(m_settings
);
501 CHANGE_BACKGROUND_COLOR(ui
->frame_header
, QColor(Qt::white
));
502 SET_PROGRESS_TEXT(tr("Encoding files, please wait..."));
504 ui
->button_closeDialog
->setEnabled(false);
505 ui
->button_AbortProcess
->setEnabled(true);
506 ui
->progressBar
->setRange(0, m_pendingJobs
.count());
507 ui
->checkBox_shutdownComputer
->setEnabled(true);
508 ui
->checkBox_shutdownComputer
->setChecked(false);
510 m_taskbar
->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_NORMAL
);
511 m_taskbar
->setTaskbarProgress(0, m_pendingJobs
.count());
512 m_taskbar
->setOverlayIcon(&QIcon(":/icons/control_play_blue.png"));
516 m_diskObserver
= new DiskObserverThread(m_settings
->customTempPathEnabled() ? m_settings
->customTempPath() : MUtils::temp_folder());
517 connect(m_diskObserver
, SIGNAL(messageLogged(QString
,int)), m_progressModel
, SLOT(addSystemMessage(QString
,int)), Qt::QueuedConnection
);
518 connect(m_diskObserver
, SIGNAL(freeSpaceChanged(quint64
)), this, SLOT(diskUsageHasChanged(quint64
)), Qt::QueuedConnection
);
519 m_diskObserver
->start();
523 m_cpuObserver
= new CPUObserverThread();
524 connect(m_cpuObserver
, SIGNAL(currentUsageChanged(double)), this, SLOT(cpuUsageHasChanged(double)), Qt::QueuedConnection
);
525 m_cpuObserver
->start();
529 m_ramObserver
= new RAMObserverThread();
530 connect(m_ramObserver
, SIGNAL(currentUsageChanged(double)), this, SLOT(ramUsageHasChanged(double)), Qt::QueuedConnection
);
531 m_ramObserver
->start();
536 unsigned int maximumInstances
= qBound(0U, m_settings
->maximumInstances(), MAX_INSTANCES
);
537 if(maximumInstances
< 1)
539 const MUtils::CPUFetaures::cpu_info_t cpuFeatures
= MUtils::CPUFetaures::detect();
540 maximumInstances
= cores2instances(qBound(1U, cpuFeatures
.count
, 64U));
543 maximumInstances
= qBound(1U, maximumInstances
, static_cast<unsigned int>(m_pendingJobs
.count()));
544 if(maximumInstances
> 1)
546 m_progressModel
->addSystemMessage(tr("Multi-threading enabled: Running %1 instances in parallel!").arg(QString::number(maximumInstances
)));
549 m_threadPool
= new QThreadPool();
550 m_threadPool
->setMaxThreadCount(maximumInstances
);
553 m_initThreads
= m_threadPool
->maxThreadCount();
554 QTimer::singleShot(100, this, SLOT(initNextJob()));
556 m_totalTime
.reset(new QElapsedTimer());
557 m_totalTime
->start();
560 void ProcessingDialog::initNextJob(void)
562 if((m_initThreads
> 0) && (!m_userAborted
))
565 if(--m_initThreads
> 0)
567 QTimer::singleShot(32, this, SLOT(initNextJob()));
572 void ProcessingDialog::startNextJob(void)
574 if(m_pendingJobs
.isEmpty())
576 qWarning("No more files left, unable to start another job!");
583 AudioFileModel currentFile
= updateMetaInfo(m_pendingJobs
.takeFirst());
584 bool nativeResampling
= false;
586 //Create encoder instance
587 AbstractEncoder
*encoder
= EncoderRegistry::createInstance(m_settings
->compressionEncoder(), m_settings
, &nativeResampling
);
589 //Create processing thread
590 ProcessThread
*thread
= new ProcessThread
593 (m_settings
->outputToSourceDir() ? QFileInfo(currentFile
.filePath()).absolutePath() : m_settings
->outputDir()),
594 (m_settings
->customTempPathEnabled() ? m_settings
->customTempPath() : MUtils::temp_folder()),
596 m_settings
->prependRelativeSourcePath() && (!m_settings
->outputToSourceDir())
600 if(m_settings
->forceStereoDownmix())
602 thread
->addFilter(new DownmixFilter());
604 if((m_settings
->samplingRate() > 0) && !nativeResampling
)
606 if(SettingsModel::samplingRates
[m_settings
->samplingRate()] != currentFile
.techInfo().audioSamplerate() || currentFile
.techInfo().audioSamplerate() == 0)
608 thread
->addFilter(new ResampleFilter(SettingsModel::samplingRates
[m_settings
->samplingRate()]));
611 if((m_settings
->toneAdjustBass() != 0) || (m_settings
->toneAdjustTreble() != 0))
613 thread
->addFilter(new ToneAdjustFilter(m_settings
->toneAdjustBass(), m_settings
->toneAdjustTreble()));
615 if(m_settings
->normalizationFilterEnabled())
617 thread
->addFilter(new NormalizeFilter(m_settings
->normalizationFilterMaxVolume(), m_settings
->normalizationFilterDynamic(), m_settings
->normalizationFilterCoupled(), m_settings
->normalizationFilterSize()));
619 if(m_settings
->renameFiles_renameEnabled() && (!m_settings
->renameFiles_renamePattern().simplified().isEmpty()))
621 thread
->setRenamePattern(m_settings
->renameFiles_renamePattern());
623 if(m_settings
->renameFiles_regExpEnabled() && (!m_settings
->renameFiles_regExpSearch().trimmed().isEmpty()) && (!m_settings
->renameFiles_regExpReplace().simplified().isEmpty()))
625 thread
->setRenameRegExp(m_settings
->renameFiles_regExpSearch(), m_settings
->renameFiles_regExpReplace());
627 if(m_settings
->overwriteMode() != SettingsModel::Overwrite_KeepBoth
)
629 thread
->setOverwriteMode((m_settings
->overwriteMode() == SettingsModel::Overwrite_SkipFile
), (m_settings
->overwriteMode() == SettingsModel::Overwrite_Replaces
));
632 m_allJobs
.append(thread
->getId());
634 //Connect thread signals
635 connect(thread
, SIGNAL(processFinished()), this, SLOT(doneEncoding()), Qt::QueuedConnection
);
636 connect(thread
, SIGNAL(processStateInitialized(QUuid
,QString
,QString
,int)), m_progressModel
, SLOT(addJob(QUuid
,QString
,QString
,int)), Qt::QueuedConnection
);
637 connect(thread
, SIGNAL(processStateChanged(QUuid
,QString
,int)), m_progressModel
, SLOT(updateJob(QUuid
,QString
,int)), Qt::QueuedConnection
);
638 connect(thread
, SIGNAL(processStateFinished(QUuid
,QString
,int)), this, SLOT(processFinished(QUuid
,QString
,int)), Qt::QueuedConnection
);
639 connect(thread
, SIGNAL(processMessageLogged(QUuid
,QString
)), m_progressModel
, SLOT(appendToLog(QUuid
,QString
)), Qt::QueuedConnection
);
640 connect(this, SIGNAL(abortRunningTasks()), thread
, SLOT(abort()), Qt::DirectConnection
);
642 //Initialize thread object
645 qFatal("Fatal Error: Thread initialization has failed!");
649 if(!thread
->start(m_threadPool
))
651 qWarning("Job failed to start or file was skipped!");
655 void ProcessingDialog::abortEncoding(bool force
)
657 m_userAborted
= true;
658 if(force
) m_forcedAbort
= true;
659 ui
->button_AbortProcess
->setEnabled(false);
660 SET_PROGRESS_TEXT(tr("Aborted! Waiting for running jobs to terminate..."));
661 emit
abortRunningTasks();
664 void ProcessingDialog::doneEncoding(void)
667 ui
->progressBar
->setValue(ui
->progressBar
->value() + 1);
671 SET_PROGRESS_TEXT(tr("Encoding: %n file(s) of %1 completed so far, please wait...", "", ui
->progressBar
->value()).arg(QString::number(ui
->progressBar
->maximum())));
672 m_taskbar
->setTaskbarProgress(ui
->progressBar
->value(), ui
->progressBar
->maximum());
675 if((!m_pendingJobs
.isEmpty()) && (!m_userAborted
))
677 QTimer::singleShot(0, this, SLOT(startNextJob()));
678 qDebug("%d files left, starting next job...", m_pendingJobs
.count());
682 if(m_runningThreads
> 0)
684 qDebug("No files left, but still have %u running jobs.", m_runningThreads
);
688 QApplication::setOverrideCursor(Qt::WaitCursor
);
689 qDebug("Running jobs: %u", m_runningThreads
);
691 if(!m_userAborted
&& m_settings
->createPlaylist() && !m_settings
->outputToSourceDir())
693 SET_PROGRESS_TEXT(tr("Creating the playlist file, please wait..."));
694 qApp
->processEvents(QEventLoop::ExcludeUserInputEvents
);
700 CHANGE_BACKGROUND_COLOR(ui
->frame_header
, QColor("#FFFFE0"));
701 m_taskbar
->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_ERROR
);
702 m_taskbar
->setOverlayIcon(&QIcon(":/icons/error.png"));
703 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!"));
704 m_systemTray
->showMessage(tr("LameXP - Aborted"), tr("Process was aborted by the user."), QSystemTrayIcon::Warning
);
705 m_systemTray
->setIcon(QIcon(":/icons/cd_delete.png"));
706 qApp
->processEvents(QEventLoop::ExcludeUserInputEvents
);
707 if(!m_forcedAbort
) PLAY_SOUND_OPTIONAL("aborted", false);
711 if((!m_totalTime
.isNull()) && m_totalTime
->isValid())
713 m_progressModel
->addSystemMessage(tr("Process finished after %1.").arg(time2text(m_totalTime
->elapsed())), ProgressModel::SysMsg_Performance
);
714 m_totalTime
->invalidate();
717 if(m_failedJobs
.count() > 0)
719 CHANGE_BACKGROUND_COLOR(ui
->frame_header
, QColor("#FFF0F0"));
720 m_taskbar
->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_ERROR
);
721 m_taskbar
->setOverlayIcon(&QIcon(":/icons/exclamation.png"));
722 if(m_skippedJobs
.count() > 0)
724 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())));
728 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())));
730 m_systemTray
->showMessage(tr("LameXP - Error"), tr("At least one file has failed!"), QSystemTrayIcon::Critical
);
731 m_systemTray
->setIcon(QIcon(":/icons/cd_delete.png"));
732 qApp
->processEvents(QEventLoop::ExcludeUserInputEvents
);
733 PLAY_SOUND_OPTIONAL("error", false);
737 CHANGE_BACKGROUND_COLOR(ui
->frame_header
, QColor("#F0FFF0"));
738 m_taskbar
->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_NORMAL
);
739 m_taskbar
->setOverlayIcon(&QIcon(":/icons/accept.png"));
740 if(m_skippedJobs
.count() > 0)
742 SET_PROGRESS_TEXT(tr("All files completed successfully. Skipped %n file(s).", "", m_skippedJobs
.count()));
746 SET_PROGRESS_TEXT(tr("All files completed successfully."));
748 m_systemTray
->showMessage(tr("LameXP - Done"), tr("All files completed successfully."), QSystemTrayIcon::Information
);
749 m_systemTray
->setIcon(QIcon(":/icons/cd_add.png"));
750 qApp
->processEvents(QEventLoop::ExcludeUserInputEvents
);
751 PLAY_SOUND_OPTIONAL("success", false);
755 MUtils::GUI::enable_close_button(this, true);
756 ui
->button_closeDialog
->setEnabled(true);
757 ui
->button_AbortProcess
->setEnabled(false);
758 ui
->checkBox_shutdownComputer
->setEnabled(false);
760 m_progressModel
->restoreHiddenItems();
761 ui
->view_log
->scrollToBottom();
762 m_progressIndicator
->stop();
763 ui
->progressBar
->setValue(ui
->progressBar
->maximum());
764 m_taskbar
->setTaskbarProgress(ui
->progressBar
->value(), ui
->progressBar
->maximum());
766 QApplication::restoreOverrideCursor();
768 if(!m_userAborted
&& ui
->checkBox_shutdownComputer
->isChecked())
770 if(shutdownComputer())
772 m_shutdownFlag
= m_settings
->hibernateComputer() ? SHUTDOWN_FLAG_HIBERNATE
: SHUTDOWN_FLAG_POWER_OFF
;
778 void ProcessingDialog::processFinished(const QUuid
&jobId
, const QString
&outFileName
, int success
)
782 m_playList
.insert(jobId
, outFileName
);
783 m_succeededJobs
.append(jobId
);
787 m_playList
.insert(jobId
, outFileName
);
788 m_skippedJobs
.append(jobId
);
792 m_failedJobs
.append(jobId
);
795 //Update filter as soon as a job finished!
796 if(m_progressViewFilter
>= 0)
798 QTimer::singleShot(0, this, SLOT(progressViewFilterChanged()));
802 void ProcessingDialog::progressModelChanged(void)
804 //Update filter as soon as the model changes!
805 if(m_progressViewFilter
>= 0)
807 QTimer::singleShot(0, this, SLOT(progressViewFilterChanged()));
810 QTimer::singleShot(0, ui
->view_log
, SLOT(scrollToBottom()));
813 void ProcessingDialog::logViewDoubleClicked(const QModelIndex
&index
)
815 if(m_runningThreads
== 0)
817 const QStringList
&logFile
= m_progressModel
->getLogFile(index
);
819 if(!logFile
.isEmpty())
821 LogViewDialog
*logView
= new LogViewDialog(this);
822 logView
->setWindowTitle(QString("LameXP - [%1]").arg(m_progressModel
->data(index
, Qt::DisplayRole
).toString()));
823 logView
->exec(logFile
);
824 MUTILS_DELETE(logView
);
828 QMessageBox::information(this, windowTitle(), m_progressModel
->data(m_progressModel
->index(index
.row(), 0)).toString());
833 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN
);
837 void ProcessingDialog::logViewSectionSizeChanged(int logicalIndex
, int oldSize
, int newSize
)
839 if(logicalIndex
== 1)
841 if(QHeaderView
*hdr
= ui
->view_log
->horizontalHeader())
843 hdr
->setMinimumSectionSize(qMax(hdr
->minimumSectionSize(), hdr
->sectionSize(1)));
848 void ProcessingDialog::contextMenuTriggered(const QPoint
&pos
)
850 QAbstractScrollArea
*scrollArea
= dynamic_cast<QAbstractScrollArea
*>(QObject::sender());
851 QWidget
*sender
= scrollArea
? scrollArea
->viewport() : dynamic_cast<QWidget
*>(QObject::sender());
853 if(pos
.x() <= sender
->width() && pos
.y() <= sender
->height() && pos
.x() >= 0 && pos
.y() >= 0)
855 m_contextMenu
->popup(sender
->mapToGlobal(pos
));
859 void ProcessingDialog::contextMenuDetailsActionTriggered(void)
861 QModelIndex index
= ui
->view_log
->indexAt(ui
->view_log
->viewport()->mapFromGlobal(m_contextMenu
->pos()));
862 logViewDoubleClicked(index
.isValid() ? index
: ui
->view_log
->currentIndex());
865 void ProcessingDialog::contextMenuShowFileActionTriggered(void)
867 QModelIndex index
= ui
->view_log
->indexAt(ui
->view_log
->viewport()->mapFromGlobal(m_contextMenu
->pos()));
868 const QUuid
&jobId
= m_progressModel
->getJobId(index
.isValid() ? index
: ui
->view_log
->currentIndex());
869 QString filePath
= m_playList
.value(jobId
, QString());
871 if(filePath
.isEmpty())
873 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN
);
877 if(QFileInfo(filePath
).exists())
879 QString systemRootPath
;
881 QDir
systemRoot(MUtils::OS::known_folder(MUtils::OS::FOLDER_SYSTEMFOLDER
));
882 if(systemRoot
.exists() && systemRoot
.cdUp())
884 systemRootPath
= systemRoot
.canonicalPath();
887 if(!systemRootPath
.isEmpty())
889 QFileInfo
explorer(QString("%1/explorer.exe").arg(systemRootPath
));
890 if(explorer
.exists() && explorer
.isFile())
892 QProcess::execute(explorer
.canonicalFilePath(), QStringList() << "/select," << QDir::toNativeSeparators(QFileInfo(filePath
).canonicalFilePath()));
898 qWarning("SystemRoot directory could not be detected!");
903 qWarning("File not found: %s", filePath
.toLatin1().constData());
904 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR
);
908 void ProcessingDialog::contextMenuFilterActionTriggered(void)
910 if(QAction
*action
= dynamic_cast<QAction
*>(QObject::sender()))
912 if(action
->data().type() == QVariant::Int
)
914 m_progressViewFilter
= action
->data().toInt();
915 progressViewFilterChanged();
916 QTimer::singleShot(0, this, SLOT(progressViewFilterChanged()));
917 QTimer::singleShot(0, ui
->view_log
, SLOT(scrollToBottom()));
918 action
->setChecked(true);
924 * Filter progress items
926 void ProcessingDialog::progressViewFilterChanged(void)
928 bool matchFound
= false;
930 for(int i
= 0; i
< ui
->view_log
->model()->rowCount(); i
++)
932 QModelIndex index
= (m_progressViewFilter
>= 0) ? m_progressModel
->index(i
, 0) : QModelIndex();
933 const bool bHide
= index
.isValid() ? (m_progressModel
->getJobState(index
) != m_progressViewFilter
) : false;
934 ui
->view_log
->setRowHidden(i
, bHide
); matchFound
= matchFound
|| (!bHide
);
937 if((m_progressViewFilter
>= 0) && (!matchFound
))
939 if(m_filterInfoLabel
->isHidden() || (dynamic_cast<IntUserData
*>(m_filterInfoLabel
->userData(0))->value() != m_progressViewFilter
))
941 dynamic_cast<IntUserData
*>(m_filterInfoLabel
->userData(0))->setValue(m_progressViewFilter
);
942 m_filterInfoLabel
->setText(QString("<p>» %1 «</p>").arg(tr("None of the items matches the current filtering rules")));
943 m_filterInfoLabel
->show();
944 m_filterInfoLabelIcon
->setPixmap(m_progressModel
->getIcon(static_cast<ProgressModel::JobState
>(m_progressViewFilter
)).pixmap(16, 16, QIcon::Disabled
));
945 m_filterInfoLabelIcon
->show();
949 else if(!m_filterInfoLabel
->isHidden())
951 m_filterInfoLabel
->hide();
952 m_filterInfoLabelIcon
->hide();
956 ////////////////////////////////////////////////////////////
958 ////////////////////////////////////////////////////////////
960 void ProcessingDialog::writePlayList(void)
962 if(m_succeededJobs
.count() <= 0 || m_allJobs
.count() <= 0)
964 qWarning("WritePlayList: Nothing to do!");
968 //Init local variables
970 QRegExp
regExp1("\\[\\d\\d\\][^/\\\\]+$", Qt::CaseInsensitive
);
971 QRegExp
regExp2("\\(\\d\\d\\)[^/\\\\]+$", Qt::CaseInsensitive
);
972 QRegExp
regExp3("\\d\\d[^/\\\\]+$", Qt::CaseInsensitive
);
973 bool usePrefix
[3] = {true, true, true};
974 bool useUtf8
= false;
977 //Generate playlist name
978 QString playListName
= (m_metaInfo
->album().isEmpty() ? "Playlist" : m_metaInfo
->album());
979 if(!m_metaInfo
->artist().isEmpty())
981 playListName
= QString("%1 - %2").arg(m_metaInfo
->artist(), playListName
);
984 //Clean playlist name
985 playListName
= MUtils::clean_file_name(playListName
);
987 //Create list of audio files
988 for(int i
= 0; i
< m_allJobs
.count(); i
++)
990 if(!m_succeededJobs
.contains(m_allJobs
.at(i
))) continue;
991 list
<< QDir::toNativeSeparators(QDir(m_settings
->outputDir()).relativeFilePath(m_playList
.value(m_allJobs
.at(i
), "N/A")));
995 for(int i
= 0; i
< list
.count(); i
++)
997 if(regExp1
.indexIn(list
.at(i
)) < 0) usePrefix
[0] = false;
998 if(regExp2
.indexIn(list
.at(i
)) < 0) usePrefix
[1] = false;
999 if(regExp3
.indexIn(list
.at(i
)) < 0) usePrefix
[2] = false;
1001 if(usePrefix
[0] || usePrefix
[1] || usePrefix
[2])
1003 playListName
.prepend(usePrefix
[0] ? "[00] " : (usePrefix
[1] ? "(00) " : "00 "));
1006 //Do we need an UTF-8 playlist?
1007 for(int i
= 0; i
< list
.count(); i
++)
1009 if(wcscmp(MUTILS_WCHR(QString::fromLatin1(list
.at(i
).toLatin1().constData())), MUTILS_WCHR(list
.at(i
))))
1016 //Generate playlist output file
1017 QString playListFile
= QString("%1/%2.%3").arg(m_settings
->outputDir(), playListName
, (useUtf8
? "m3u8" : "m3u"));
1018 while(QFileInfo(playListFile
).exists())
1020 playListFile
= QString("%1/%2 (%3).%4").arg(m_settings
->outputDir(), playListName
, QString::number(++counter
), (useUtf8
? "m3u8" : "m3u"));
1023 //Now write playlist to output file
1024 QFile
playList(playListFile
);
1025 if(playList
.open(QIODevice::WriteOnly
))
1029 playList
.write("\xef\xbb\xbf");
1031 playList
.write("#EXTM3U\r\n");
1032 while(!list
.isEmpty())
1034 playList
.write(useUtf8
? MUTILS_UTF8(list
.takeFirst()) : list
.takeFirst().toLatin1().constData());
1035 playList
.write("\r\n");
1041 QMessageBox::warning(this, tr("Playlist creation failed"), QString("%1<br><nobr>%2</nobr>").arg(tr("The playlist file could not be created:"), playListFile
));
1045 AudioFileModel
ProcessingDialog::updateMetaInfo(AudioFileModel
&audioFile
)
1047 if(!m_settings
->writeMetaTags())
1049 audioFile
.metaInfo().reset();
1053 audioFile
.metaInfo().update(*m_metaInfo
, true);
1055 if(audioFile
.metaInfo().position() == UINT_MAX
)
1057 audioFile
.metaInfo().setPosition(m_currentFile
);
1063 void ProcessingDialog::systemTrayActivated(QSystemTrayIcon::ActivationReason reason
)
1065 if(reason
== QSystemTrayIcon::DoubleClick
)
1067 MUtils::GUI::bring_to_front(this);
1071 void ProcessingDialog::cpuUsageHasChanged(const double val
)
1074 ui
->label_cpu
->setText(QString().sprintf(" %d%%", qRound(val
* 100.0)));
1075 UPDATE_MIN_WIDTH(ui
->label_cpu
);
1078 void ProcessingDialog::ramUsageHasChanged(const double val
)
1081 ui
->label_ram
->setText(QString().sprintf(" %d%%", qRound(val
* 100.0)));
1082 UPDATE_MIN_WIDTH(ui
->label_ram
);
1085 void ProcessingDialog::diskUsageHasChanged(const quint64 val
)
1088 const char *postfixStr
[6] = {"B", "KB", "MB", "GB", "TB", "PB"};
1089 double space
= static_cast<double>(val
);
1091 while((space
>= 1000.0) && (postfix
< 5))
1093 space
= space
/ 1024.0;
1097 ui
->label_disk
->setText(QString().sprintf(" %3.1f %s", space
, postfixStr
[postfix
]));
1098 UPDATE_MIN_WIDTH(ui
->label_disk
);
1101 bool ProcessingDialog::shutdownComputer(void)
1103 const int iTimeout
= m_settings
->hibernateComputer() ? 10 : 30;
1104 const Qt::WindowFlags flags
= Qt::WindowStaysOnTopHint
| Qt::CustomizeWindowHint
| Qt::WindowTitleHint
| Qt::MSWindowsFixedSizeDialogHint
| Qt::WindowSystemMenuHint
;
1105 const QString text
= QString("%1%2%1").arg(QString().fill(' ', 18), tr("Warning: Computer will shutdown in %1 seconds..."));
1107 qWarning("Initiating shutdown sequence!");
1109 QProgressDialog
progressDialog(text
.arg(iTimeout
), tr("Cancel Shutdown"), 0, iTimeout
+ 1, this, flags
);
1110 QPushButton
*cancelButton
= new QPushButton(tr("Cancel Shutdown"), &progressDialog
);
1111 cancelButton
->setIcon(QIcon(":/icons/power_on.png"));
1112 progressDialog
.setModal(true);
1113 progressDialog
.setAutoClose(false);
1114 progressDialog
.setAutoReset(false);
1115 progressDialog
.setWindowIcon(QIcon(":/icons/power_off.png"));
1116 progressDialog
.setCancelButton(cancelButton
);
1117 progressDialog
.show();
1119 qApp
->processEvents(QEventLoop::ExcludeUserInputEvents
);
1121 QApplication::setOverrideCursor(Qt::WaitCursor
);
1122 PLAY_SOUND_OPTIONAL("shutdown", false);
1123 QApplication::restoreOverrideCursor();
1126 timer
.setInterval(1000);
1129 QEventLoop
eventLoop(this);
1130 connect(&timer
, SIGNAL(timeout()), &eventLoop
, SLOT(quit()));
1131 connect(&progressDialog
, SIGNAL(canceled()), &eventLoop
, SLOT(quit()));
1133 for(int i
= 1; i
<= iTimeout
; i
++)
1136 if(progressDialog
.wasCanceled())
1138 progressDialog
.close();
1141 progressDialog
.setValue(i
+1);
1142 progressDialog
.setLabelText(text
.arg(iTimeout
-i
));
1143 if(iTimeout
-i
== 3) progressDialog
.setCancelButton(NULL
);
1144 qApp
->processEvents(QEventLoop::ExcludeUserInputEvents
);
1145 PLAY_SOUND_OPTIONAL(((i
< iTimeout
) ? "beep" : "beep2"), false);
1148 progressDialog
.close();
1152 QString
ProcessingDialog::time2text(const qint64
&msec
) const
1154 const qint64 MILLISECONDS_PER_DAY
= 86399999; //24x60x60x1000 - 1
1155 const QTime time
= QTime().addMSecs(qMin(msec
, MILLISECONDS_PER_DAY
));
1161 a
= tr("%n hour(s)", "", time
.hour());
1162 b
= tr("%n minute(s)", "", time
.minute());
1164 else if(time
.minute() > 0)
1166 a
= tr("%n minute(s)", "", time
.minute());
1167 b
= tr("%n second(s)", "", time
.second());
1171 a
= tr("%n second(s)", "", time
.second());
1172 b
= tr("%n millisecond(s)", "", time
.msec());
1175 return QString("%1, %2").arg(a
, b
);
1178 ////////////////////////////////////////////////////////////
1180 ////////////////////////////////////////////////////////////
1182 static int cores2instances(int cores
)
1184 //This function is a "cubic spline" with sampling points at:
1185 //(1,1); (2,2); (4,4); (8,6); (16,8); (32,11); (64,16)
1186 static const double LUT
[8][5] =
1188 { 1.0, 0.014353554, -0.043060662, 1.028707108, 0.000000000},
1189 { 2.0, -0.028707108, 0.215303309, 0.511979167, 0.344485294},
1190 { 4.0, 0.010016468, -0.249379596, 2.370710784, -2.133823529},
1191 { 8.0, 0.000282437, -0.015762868, 0.501776961, 2.850000000},
1192 {16.0, 0.000033270, -0.003802849, 0.310416667, 3.870588235},
1193 {32.0, 0.000006343, -0.001217831, 0.227696078, 4.752941176},
1194 {64.0, 0.000000000, 0.000000000, 0.000000000, 16.000000000},
1195 {DBL_MAX
, 0.0, 0.0, 0.0, 0.0}
1198 double x
= abs(static_cast<double>(cores
)), y
= 1.0;
1200 for(size_t i
= 0; i
< 7; i
++)
1202 if((x
>= LUT
[i
][0]) && (x
< LUT
[i
+1][0]))
1204 y
= (((((LUT
[i
][1] * x
) + LUT
[i
][2]) * x
) + LUT
[i
][3]) * x
) + LUT
[i
][4];