Adapt for latest MUtils changes.
[LameXP.git] / src / Dialog_MainWindow.cpp
blobe237a59d6a3f032c77fd545e42595035dfae0063
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2016 LoRd_MuldeR <MuldeR2@GMX.de>
4 //
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; either version 2 of the License, or
8 // (at your option) any later version, but always including the *additional*
9 // restrictions defined in the "License.txt" file.
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_MainWindow.h"
25 //UIC includes
26 #include "UIC_MainWindow.h"
28 //LameXP includes
29 #include "Global.h"
30 #include "Dialog_WorkingBanner.h"
31 #include "Dialog_MetaInfo.h"
32 #include "Dialog_About.h"
33 #include "Dialog_Update.h"
34 #include "Dialog_DropBox.h"
35 #include "Dialog_CueImport.h"
36 #include "Dialog_LogView.h"
37 #include "Thread_FileAnalyzer.h"
38 #include "Thread_MessageHandler.h"
39 #include "Model_MetaInfo.h"
40 #include "Model_Settings.h"
41 #include "Model_FileList.h"
42 #include "Model_FileSystem.h"
43 #include "Model_FileExts.h"
44 #include "Registry_Encoder.h"
45 #include "Registry_Decoder.h"
46 #include "Encoder_Abstract.h"
47 #include "ShellIntegration.h"
48 #include "CustomEventFilter.h"
50 //Mutils includes
51 #include <MUtils/Global.h>
52 #include <MUtils/OSSupport.h>
53 #include <MUtils/GUI.h>
54 #include <MUtils/Exception.h>
55 #include <MUtils/Sound.h>
56 #include <MUtils/Translation.h>
57 #include <MUtils/Version.h>
59 //Qt includes
60 #include <QMessageBox>
61 #include <QTimer>
62 #include <QDesktopWidget>
63 #include <QDate>
64 #include <QFileDialog>
65 #include <QInputDialog>
66 #include <QFileSystemModel>
67 #include <QDesktopServices>
68 #include <QUrl>
69 #include <QPlastiqueStyle>
70 #include <QCleanlooksStyle>
71 #include <QWindowsVistaStyle>
72 #include <QWindowsStyle>
73 #include <QSysInfo>
74 #include <QDragEnterEvent>
75 #include <QMimeData>
76 #include <QProcess>
77 #include <QUuid>
78 #include <QProcessEnvironment>
79 #include <QCryptographicHash>
80 #include <QTranslator>
81 #include <QResource>
82 #include <QScrollBar>
84 ////////////////////////////////////////////////////////////
85 // Constants
86 ////////////////////////////////////////////////////////////
88 static const unsigned int IDM_ABOUTBOX = 0xEFF0;
89 static const char *g_hydrogen_audio_url = "http://wiki.hydrogenaud.io/index.php?title=Main_Page";
90 static const char *g_documents_base_url = "http://lamexp.sourceforge.net/doc";
92 ////////////////////////////////////////////////////////////
93 // Helper Macros
94 ////////////////////////////////////////////////////////////
96 #define BANNER_VISIBLE ((!m_banner.isNull()) && m_banner->isVisible())
98 #define INIT_BANNER() do \
99 { \
100 if(m_banner.isNull()) \
102 m_banner.reset(new WorkingBanner(this)); \
105 while(0)
107 #define ABORT_IF_BUSY do \
109 if(BANNER_VISIBLE || m_delayedFileTimer->isActive() || (QApplication::activeModalWidget() != NULL)) \
111 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN); \
112 return; \
115 while(0)
117 #define PLAY_SOUND_OPTIONAL(NAME, ASYNC) do \
119 if(m_settings->soundsEnabled()) MUtils::Sound::play_sound((NAME), (ASYNC)); \
121 while(0)
123 #define SHOW_CORNER_WIDGET(FLAG) do \
125 if(QWidget *cornerWidget = ui->menubar->cornerWidget()) \
127 cornerWidget->setVisible((FLAG)); \
130 while(0)
132 #define LINK(URL) \
133 (QString("<a href=\"%1\">%2</a>").arg(URL).arg(QString(URL).replace("-", "&minus;")))
135 #define LINK_EX(URL, NAME) \
136 (QString("<a href=\"%1\">%2</a>").arg(URL).arg(QString(NAME).replace("-", "&minus;")))
138 #define FSLINK(PATH) \
139 (QString("<a href=\"file:///%1\">%2</a>").arg(PATH).arg(QString(PATH).replace("-", "&minus;")))
141 #define CENTER_CURRENT_OUTPUT_FOLDER_DELAYED() \
142 QTimer::singleShot(125, this, SLOT(centerOutputFolderModel()))
144 ////////////////////////////////////////////////////////////
145 // Static Functions
146 ////////////////////////////////////////////////////////////
148 static inline void SET_TEXT_COLOR(QWidget *const widget, const QColor &color)
150 QPalette _palette = widget->palette();
151 _palette.setColor(QPalette::WindowText, (color));
152 _palette.setColor(QPalette::Text, (color));
153 widget->setPalette(_palette);
156 static inline void SET_FONT_BOLD(QWidget *const widget, const bool &bold)
158 QFont _font = widget->font();
159 _font.setBold(bold);
160 widget->setFont(_font);
163 static inline void SET_FONT_BOLD(QAction *const widget, const bool &bold)
165 QFont _font = widget->font();
166 _font.setBold(bold);
167 widget->setFont(_font);
170 static inline void SET_MODEL(QAbstractItemView *const view, QAbstractItemModel *const model)
172 QItemSelectionModel *_tmp = view->selectionModel();
173 view->setModel(model);
174 MUTILS_DELETE(_tmp);
177 static inline void SET_CHECKBOX_STATE(QCheckBox *const chckbx, const bool &state)
179 const bool isDisabled = (!chckbx->isEnabled());
180 if(isDisabled)
182 chckbx->setEnabled(true);
184 if(chckbx->isChecked() != state)
186 chckbx->click();
188 if(chckbx->isChecked() != state)
190 qWarning("Warning: Failed to set checkbox %p state!", chckbx);
192 if(isDisabled)
194 chckbx->setEnabled(false);
198 static inline void TRIM_STRING_RIGHT(QString &str)
200 while((str.length() > 0) && str[str.length()-1].isSpace())
202 str.chop(1);
206 static inline void MAKE_TRANSPARENT(QWidget *const widget, const bool &flag)
208 QPalette _p = widget->palette(); \
209 _p.setColor(QPalette::Background, Qt::transparent);
210 widget->setPalette(flag ? _p : QPalette());
213 template <typename T>
214 static QList<T>& INVERT_LIST(QList<T> &list)
216 if(!list.isEmpty())
218 const int limit = list.size() / 2, maxIdx = list.size() - 1;
219 for(int k = 0; k < limit; k++) list.swap(k, maxIdx - k);
221 return list;
224 ////////////////////////////////////////////////////////////
225 // Helper Classes
226 ////////////////////////////////////////////////////////////
228 class WidgetHideHelper
230 public:
231 WidgetHideHelper(QWidget *const widget) : m_widget(widget), m_visible(widget && widget->isVisible()) { if(m_widget && m_visible) m_widget->hide(); }
232 ~WidgetHideHelper(void) { if(m_widget && m_visible) m_widget->show(); }
233 private:
234 QWidget *const m_widget;
235 const bool m_visible;
238 class SignalBlockHelper
240 public:
241 SignalBlockHelper(QObject *const object) : m_object(object), m_flag(object && object->blockSignals(true)) {}
242 ~SignalBlockHelper(void) { if(m_object && (!m_flag)) m_object->blockSignals(false); }
243 private:
244 QObject *const m_object;
245 const bool m_flag;
248 class FileListBlockHelper
250 public:
251 FileListBlockHelper(FileListModel *const fileList) : m_fileList(fileList) { if(m_fileList) m_fileList->setBlockUpdates(true); }
252 ~FileListBlockHelper(void) { if(m_fileList) m_fileList->setBlockUpdates(false); }
253 private:
254 FileListModel *const m_fileList;
257 ////////////////////////////////////////////////////////////
258 // Constructor
259 ////////////////////////////////////////////////////////////
261 MainWindow::MainWindow(MUtils::IPCChannel *const ipcChannel, FileListModel *const fileListModel, AudioFileModel_MetaInfo *const metaInfo, SettingsModel *const settingsModel, QWidget *const parent)
263 QMainWindow(parent),
264 ui(new Ui::MainWindow),
265 m_fileListModel(fileListModel),
266 m_metaData(metaInfo),
267 m_settings(settingsModel),
268 m_accepted(false),
269 m_firstTimeShown(true),
270 m_outputFolderViewCentering(false),
271 m_outputFolderViewInitCounter(0)
273 //Init the dialog, from the .ui file
274 ui->setupUi(this);
275 setWindowFlags(windowFlags() ^ Qt::WindowMaximizeButtonHint);
277 //Create window icon
278 MUtils::GUI::set_window_icon(this, lamexp_app_icon(), true);
280 //Register meta types
281 qRegisterMetaType<AudioFileModel>("AudioFileModel");
283 //Enabled main buttons
284 connect(ui->buttonAbout, SIGNAL(clicked()), this, SLOT(aboutButtonClicked()));
285 connect(ui->buttonStart, SIGNAL(clicked()), this, SLOT(encodeButtonClicked()));
286 connect(ui->buttonQuit, SIGNAL(clicked()), this, SLOT(closeButtonClicked()));
288 //Setup tab widget
289 ui->tabWidget->setCurrentIndex(0);
290 connect(ui->tabWidget, SIGNAL(currentChanged(int)), this, SLOT(tabPageChanged(int)));
292 //Add system menu
293 MUtils::GUI::sysmenu_append(this, IDM_ABOUTBOX, "About...");
295 //Setup corner widget
296 QLabel *cornerWidget = new QLabel(ui->menubar);
297 m_evenFilterCornerWidget.reset(new CustomEventFilter);
298 cornerWidget->setText("N/A");
299 cornerWidget->setFixedHeight(ui->menubar->height());
300 cornerWidget->setCursor(QCursor(Qt::PointingHandCursor));
301 cornerWidget->hide();
302 cornerWidget->installEventFilter(m_evenFilterCornerWidget.data());
303 connect(m_evenFilterCornerWidget.data(), SIGNAL(eventOccurred(QWidget*, QEvent*)), this, SLOT(cornerWidgetEventOccurred(QWidget*, QEvent*)));
304 ui->menubar->setCornerWidget(cornerWidget);
306 //--------------------------------
307 // Setup "Source" tab
308 //--------------------------------
310 ui->sourceFileView->setModel(m_fileListModel);
311 ui->sourceFileView->verticalHeader() ->setResizeMode(QHeaderView::ResizeToContents);
312 ui->sourceFileView->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);
313 ui->sourceFileView->setContextMenuPolicy(Qt::CustomContextMenu);
314 ui->sourceFileView->viewport()->installEventFilter(this);
315 m_dropNoteLabel.reset(new QLabel(ui->sourceFileView));
316 m_dropNoteLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
317 SET_FONT_BOLD(m_dropNoteLabel.data(), true);
318 SET_TEXT_COLOR(m_dropNoteLabel.data(), Qt::darkGray);
319 m_sourceFilesContextMenu.reset(new QMenu());
320 m_showDetailsContextAction = m_sourceFilesContextMenu->addAction(QIcon(":/icons/zoom.png"), "N/A");
321 m_previewContextAction = m_sourceFilesContextMenu->addAction(QIcon(":/icons/sound.png"), "N/A");
322 m_findFileContextAction = m_sourceFilesContextMenu->addAction(QIcon(":/icons/folder_go.png"), "N/A");
323 m_sourceFilesContextMenu->addSeparator();
324 m_exportCsvContextAction = m_sourceFilesContextMenu->addAction(QIcon(":/icons/table_save.png"), "N/A");
325 m_importCsvContextAction = m_sourceFilesContextMenu->addAction(QIcon(":/icons/folder_table.png"), "N/A");
326 SET_FONT_BOLD(m_showDetailsContextAction, true);
328 connect(ui->buttonAddFiles, SIGNAL(clicked()), this, SLOT(addFilesButtonClicked()));
329 connect(ui->buttonRemoveFile, SIGNAL(clicked()), this, SLOT(removeFileButtonClicked()));
330 connect(ui->buttonClearFiles, SIGNAL(clicked()), this, SLOT(clearFilesButtonClicked()));
331 connect(ui->buttonFileUp, SIGNAL(clicked()), this, SLOT(fileUpButtonClicked()));
332 connect(ui->buttonFileDown, SIGNAL(clicked()), this, SLOT(fileDownButtonClicked()));
333 connect(ui->buttonShowDetails, SIGNAL(clicked()), this, SLOT(showDetailsButtonClicked()));
334 connect(m_fileListModel, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(sourceModelChanged()));
335 connect(m_fileListModel, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(sourceModelChanged()));
336 connect(m_fileListModel, SIGNAL(modelReset()), this, SLOT(sourceModelChanged()));
337 connect(ui->sourceFileView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(sourceFilesContextMenu(QPoint)));
338 connect(ui->sourceFileView->verticalScrollBar(), SIGNAL(sliderMoved(int)), this, SLOT(sourceFilesScrollbarMoved(int)));
339 connect(ui->sourceFileView->verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(sourceFilesScrollbarMoved(int)));
340 connect(m_showDetailsContextAction, SIGNAL(triggered(bool)), this, SLOT(showDetailsButtonClicked()));
341 connect(m_previewContextAction, SIGNAL(triggered(bool)), this, SLOT(previewContextActionTriggered()));
342 connect(m_findFileContextAction, SIGNAL(triggered(bool)), this, SLOT(findFileContextActionTriggered()));
343 connect(m_exportCsvContextAction, SIGNAL(triggered(bool)), this, SLOT(exportCsvContextActionTriggered()));
344 connect(m_importCsvContextAction, SIGNAL(triggered(bool)), this, SLOT(importCsvContextActionTriggered()));
346 //--------------------------------
347 // Setup "Output" tab
348 //--------------------------------
350 ui->outputFolderView->setHeaderHidden(true);
351 ui->outputFolderView->setAnimated(false);
352 ui->outputFolderView->setMouseTracking(false);
353 ui->outputFolderView->setContextMenuPolicy(Qt::CustomContextMenu);
354 ui->outputFolderView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
356 m_evenFilterOutputFolderMouse.reset(new CustomEventFilter);
357 ui->outputFoldersGoUpLabel ->installEventFilter(m_evenFilterOutputFolderMouse.data());
358 ui->outputFoldersEditorLabel ->installEventFilter(m_evenFilterOutputFolderMouse.data());
359 ui->outputFoldersFovoritesLabel->installEventFilter(m_evenFilterOutputFolderMouse.data());
360 ui->outputFolderLabel ->installEventFilter(m_evenFilterOutputFolderMouse.data());
362 m_evenFilterOutputFolderView.reset(new CustomEventFilter);
363 ui->outputFolderView->installEventFilter(m_evenFilterOutputFolderView.data());
365 SET_CHECKBOX_STATE(ui->saveToSourceFolderCheckBox, m_settings->outputToSourceDir());
366 ui->prependRelativePathCheckBox->setChecked(m_settings->prependRelativeSourcePath());
368 connect(ui->outputFolderView, SIGNAL(clicked(QModelIndex)), this, SLOT(outputFolderViewClicked(QModelIndex)));
369 connect(ui->outputFolderView, SIGNAL(activated(QModelIndex)), this, SLOT(outputFolderViewClicked(QModelIndex)));
370 connect(ui->outputFolderView, SIGNAL(pressed(QModelIndex)), this, SLOT(outputFolderViewClicked(QModelIndex)));
371 connect(ui->outputFolderView, SIGNAL(entered(QModelIndex)), this, SLOT(outputFolderViewMoved(QModelIndex)));
372 connect(ui->outputFolderView, SIGNAL(expanded(QModelIndex)), this, SLOT(outputFolderItemExpanded(QModelIndex)));
373 connect(ui->buttonMakeFolder, SIGNAL(clicked()), this, SLOT(makeFolderButtonClicked()));
374 connect(ui->buttonGotoHome, SIGNAL(clicked()), this, SLOT(gotoHomeFolderButtonClicked()));
375 connect(ui->buttonGotoDesktop, SIGNAL(clicked()), this, SLOT(gotoDesktopButtonClicked()));
376 connect(ui->buttonGotoMusic, SIGNAL(clicked()), this, SLOT(gotoMusicFolderButtonClicked()));
377 connect(ui->saveToSourceFolderCheckBox, SIGNAL(clicked()), this, SLOT(saveToSourceFolderChanged()));
378 connect(ui->prependRelativePathCheckBox, SIGNAL(clicked()), this, SLOT(prependRelativePathChanged()));
379 connect(ui->outputFolderEdit, SIGNAL(editingFinished()), this, SLOT(outputFolderEditFinished()));
380 connect(m_evenFilterOutputFolderMouse.data(), SIGNAL(eventOccurred(QWidget*, QEvent*)), this, SLOT(outputFolderMouseEventOccurred(QWidget*, QEvent*)));
381 connect(m_evenFilterOutputFolderView.data(), SIGNAL(eventOccurred(QWidget*, QEvent*)), this, SLOT(outputFolderViewEventOccurred(QWidget*, QEvent*)));
383 m_outputFolderContextMenu.reset(new QMenu());
384 m_showFolderContextAction = m_outputFolderContextMenu->addAction(QIcon(":/icons/zoom.png"), "N/A");
385 m_goUpFolderContextAction = m_outputFolderContextMenu->addAction(QIcon(":/icons/folder_up.png"), "N/A");
386 m_outputFolderContextMenu->addSeparator();
387 m_refreshFolderContextAction = m_outputFolderContextMenu->addAction(QIcon(":/icons/arrow_refresh.png"), "N/A");
388 m_outputFolderContextMenu->setDefaultAction(m_showFolderContextAction);
389 connect(ui->outputFolderView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(outputFolderContextMenu(QPoint)));
390 connect(m_showFolderContextAction, SIGNAL(triggered(bool)), this, SLOT(showFolderContextActionTriggered()));
391 connect(m_refreshFolderContextAction, SIGNAL(triggered(bool)), this, SLOT(refreshFolderContextActionTriggered()));
392 connect(m_goUpFolderContextAction, SIGNAL(triggered(bool)), this, SLOT(goUpFolderContextActionTriggered()));
394 m_outputFolderFavoritesMenu.reset(new QMenu());
395 m_addFavoriteFolderAction = m_outputFolderFavoritesMenu->addAction(QIcon(":/icons/add.png"), "N/A");
396 m_outputFolderFavoritesMenu->insertSeparator(m_addFavoriteFolderAction);
397 connect(m_addFavoriteFolderAction, SIGNAL(triggered(bool)), this, SLOT(addFavoriteFolderActionTriggered()));
399 ui->outputFolderEdit->setVisible(false);
400 m_outputFolderNoteBox.reset(new QLabel(ui->outputFolderView));
401 m_outputFolderNoteBox->setAutoFillBackground(true);
402 m_outputFolderNoteBox->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
403 m_outputFolderNoteBox->setFrameShape(QFrame::StyledPanel);
404 SET_FONT_BOLD(m_outputFolderNoteBox.data(), true);
405 m_outputFolderNoteBox->hide();
407 outputFolderViewClicked(QModelIndex());
408 refreshFavorites();
410 //--------------------------------
411 // Setup "Meta Data" tab
412 //--------------------------------
414 m_metaInfoModel.reset(new MetaInfoModel(m_metaData));
415 m_metaInfoModel->clearData();
416 m_metaInfoModel->setData(m_metaInfoModel->index(4, 1), m_settings->metaInfoPosition());
417 ui->metaDataView->setModel(m_metaInfoModel.data());
418 ui->metaDataView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
419 ui->metaDataView->verticalHeader()->hide();
420 ui->metaDataView->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);
421 SET_CHECKBOX_STATE(ui->writeMetaDataCheckBox, m_settings->writeMetaTags());
422 ui->generatePlaylistCheckBox->setChecked(m_settings->createPlaylist());
423 connect(ui->buttonEditMeta, SIGNAL(clicked()), this, SLOT(editMetaButtonClicked()));
424 connect(ui->buttonClearMeta, SIGNAL(clicked()), this, SLOT(clearMetaButtonClicked()));
425 connect(ui->writeMetaDataCheckBox, SIGNAL(clicked()), this, SLOT(metaTagsEnabledChanged()));
426 connect(ui->generatePlaylistCheckBox, SIGNAL(clicked()), this, SLOT(playlistEnabledChanged()));
428 //--------------------------------
429 //Setup "Compression" tab
430 //--------------------------------
432 m_encoderButtonGroup.reset(new QButtonGroup(this));
433 m_encoderButtonGroup->addButton(ui->radioButtonEncoderMP3, SettingsModel::MP3Encoder);
434 m_encoderButtonGroup->addButton(ui->radioButtonEncoderVorbis, SettingsModel::VorbisEncoder);
435 m_encoderButtonGroup->addButton(ui->radioButtonEncoderAAC, SettingsModel::AACEncoder);
436 m_encoderButtonGroup->addButton(ui->radioButtonEncoderAC3, SettingsModel::AC3Encoder);
437 m_encoderButtonGroup->addButton(ui->radioButtonEncoderFLAC, SettingsModel::FLACEncoder);
438 m_encoderButtonGroup->addButton(ui->radioButtonEncoderAPE, SettingsModel::MACEncoder);
439 m_encoderButtonGroup->addButton(ui->radioButtonEncoderOpus, SettingsModel::OpusEncoder);
440 m_encoderButtonGroup->addButton(ui->radioButtonEncoderDCA, SettingsModel::DCAEncoder);
441 m_encoderButtonGroup->addButton(ui->radioButtonEncoderPCM, SettingsModel::PCMEncoder);
443 const int aacEncoder = EncoderRegistry::getAacEncoder();
444 ui->radioButtonEncoderAAC->setEnabled(aacEncoder > SettingsModel::AAC_ENCODER_NONE);
446 m_modeButtonGroup.reset(new QButtonGroup(this));
447 m_modeButtonGroup->addButton(ui->radioButtonModeQuality, SettingsModel::VBRMode);
448 m_modeButtonGroup->addButton(ui->radioButtonModeAverageBitrate, SettingsModel::ABRMode);
449 m_modeButtonGroup->addButton(ui->radioButtonConstBitrate, SettingsModel::CBRMode);
451 ui->radioButtonEncoderMP3->setChecked(true);
452 foreach(QAbstractButton *currentButton, m_encoderButtonGroup->buttons())
454 if(currentButton->isEnabled() && (m_encoderButtonGroup->id(currentButton) == m_settings->compressionEncoder()))
456 currentButton->setChecked(true);
457 break;
461 m_evenFilterCompressionTab.reset(new CustomEventFilter());
462 ui->labelCompressionHelp->installEventFilter(m_evenFilterCompressionTab.data());
463 ui->labelResetEncoders ->installEventFilter(m_evenFilterCompressionTab.data());
465 connect(m_encoderButtonGroup.data(), SIGNAL(buttonClicked(int)), this, SLOT(updateEncoder(int)));
466 connect(m_modeButtonGroup.data(), SIGNAL(buttonClicked(int)), this, SLOT(updateRCMode(int)));
467 connect(m_evenFilterCompressionTab.data(), SIGNAL(eventOccurred(QWidget*, QEvent*)), this, SLOT(compressionTabEventOccurred(QWidget*, QEvent*)));
468 connect(ui->sliderBitrate, SIGNAL(valueChanged(int)), this, SLOT(updateBitrate(int)));
470 updateEncoder(m_encoderButtonGroup->checkedId());
472 //--------------------------------
473 //Setup "Advanced Options" tab
474 //--------------------------------
476 ui->sliderLameAlgoQuality->setValue(m_settings->lameAlgoQuality());
477 if(m_settings->maximumInstances() > 0) ui->sliderMaxInstances->setValue(m_settings->maximumInstances());
479 ui->spinBoxBitrateManagementMin ->setValue(m_settings->bitrateManagementMinRate());
480 ui->spinBoxBitrateManagementMax ->setValue(m_settings->bitrateManagementMaxRate());
481 ui->spinBoxNormalizationFilterPeak->setValue(static_cast<double>(m_settings->normalizationFilterMaxVolume()) / 100.0);
482 ui->spinBoxNormalizationFilterSize->setValue(m_settings->normalizationFilterSize());
483 ui->spinBoxToneAdjustBass ->setValue(static_cast<double>(m_settings->toneAdjustBass()) / 100.0);
484 ui->spinBoxToneAdjustTreble ->setValue(static_cast<double>(m_settings->toneAdjustTreble()) / 100.0);
485 ui->spinBoxAftenSearchSize ->setValue(m_settings->aftenExponentSearchSize());
486 ui->spinBoxOpusComplexity ->setValue(m_settings->opusComplexity());
488 ui->comboBoxMP3ChannelMode ->setCurrentIndex(m_settings->lameChannelMode());
489 ui->comboBoxSamplingRate ->setCurrentIndex(m_settings->samplingRate());
490 ui->comboBoxAACProfile ->setCurrentIndex(m_settings->aacEncProfile());
491 ui->comboBoxAftenCodingMode ->setCurrentIndex(m_settings->aftenAudioCodingMode());
492 ui->comboBoxAftenDRCMode ->setCurrentIndex(m_settings->aftenDynamicRangeCompression());
493 ui->comboBoxOpusFramesize ->setCurrentIndex(m_settings->opusFramesize());
495 SET_CHECKBOX_STATE(ui->checkBoxBitrateManagement, m_settings->bitrateManagementEnabled());
496 SET_CHECKBOX_STATE(ui->checkBoxNeroAAC2PassMode, m_settings->neroAACEnable2Pass());
497 SET_CHECKBOX_STATE(ui->checkBoxAftenFastAllocation, m_settings->aftenFastBitAllocation());
498 SET_CHECKBOX_STATE(ui->checkBoxNormalizationFilterEnabled, m_settings->normalizationFilterEnabled());
499 SET_CHECKBOX_STATE(ui->checkBoxNormalizationFilterDynamic, m_settings->normalizationFilterDynamic());
500 SET_CHECKBOX_STATE(ui->checkBoxNormalizationFilterCoupled, m_settings->normalizationFilterCoupled());
501 SET_CHECKBOX_STATE(ui->checkBoxAutoDetectInstances, (m_settings->maximumInstances() < 1));
502 SET_CHECKBOX_STATE(ui->checkBoxUseSystemTempFolder, (!m_settings->customTempPathEnabled()));
503 SET_CHECKBOX_STATE(ui->checkBoxRename_Rename, m_settings->renameFiles_renameEnabled());
504 SET_CHECKBOX_STATE(ui->checkBoxRename_RegExp, m_settings->renameFiles_regExpEnabled());
505 SET_CHECKBOX_STATE(ui->checkBoxForceStereoDownmix, m_settings->forceStereoDownmix());
506 SET_CHECKBOX_STATE(ui->checkBoxOpusDisableResample, m_settings->opusDisableResample());
507 SET_CHECKBOX_STATE(ui->checkBoxKeepOriginalDateTime, m_settings->keepOriginalDataTime());
509 ui->checkBoxNeroAAC2PassMode->setEnabled(aacEncoder == SettingsModel::AAC_ENCODER_NERO);
511 ui->lineEditCustomParamLAME ->setText(EncoderRegistry::loadEncoderCustomParams(m_settings, SettingsModel::MP3Encoder));
512 ui->lineEditCustomParamOggEnc ->setText(EncoderRegistry::loadEncoderCustomParams(m_settings, SettingsModel::VorbisEncoder));
513 ui->lineEditCustomParamNeroAAC ->setText(EncoderRegistry::loadEncoderCustomParams(m_settings, SettingsModel::AACEncoder));
514 ui->lineEditCustomParamFLAC ->setText(EncoderRegistry::loadEncoderCustomParams(m_settings, SettingsModel::FLACEncoder));
515 ui->lineEditCustomParamAften ->setText(EncoderRegistry::loadEncoderCustomParams(m_settings, SettingsModel::AC3Encoder));
516 ui->lineEditCustomParamOpus ->setText(EncoderRegistry::loadEncoderCustomParams(m_settings, SettingsModel::OpusEncoder));
517 ui->lineEditCustomTempFolder ->setText(QDir::toNativeSeparators(m_settings->customTempPath()));
518 ui->lineEditRenamePattern ->setText(m_settings->renameFiles_renamePattern());
519 ui->lineEditRenameRegExp_Search ->setText(m_settings->renameFiles_regExpSearch ());
520 ui->lineEditRenameRegExp_Replace->setText(m_settings->renameFiles_regExpReplace());
522 m_evenFilterCustumParamsHelp.reset(new CustomEventFilter());
523 ui->helpCustomParamLAME ->installEventFilter(m_evenFilterCustumParamsHelp.data());
524 ui->helpCustomParamOggEnc ->installEventFilter(m_evenFilterCustumParamsHelp.data());
525 ui->helpCustomParamNeroAAC->installEventFilter(m_evenFilterCustumParamsHelp.data());
526 ui->helpCustomParamFLAC ->installEventFilter(m_evenFilterCustumParamsHelp.data());
527 ui->helpCustomParamAften ->installEventFilter(m_evenFilterCustumParamsHelp.data());
528 ui->helpCustomParamOpus ->installEventFilter(m_evenFilterCustumParamsHelp.data());
530 m_overwriteButtonGroup.reset(new QButtonGroup(this));
531 m_overwriteButtonGroup->addButton(ui->radioButtonOverwriteModeKeepBoth, SettingsModel::Overwrite_KeepBoth);
532 m_overwriteButtonGroup->addButton(ui->radioButtonOverwriteModeSkipFile, SettingsModel::Overwrite_SkipFile);
533 m_overwriteButtonGroup->addButton(ui->radioButtonOverwriteModeReplaces, SettingsModel::Overwrite_Replaces);
535 ui->radioButtonOverwriteModeKeepBoth->setChecked(m_settings->overwriteMode() == SettingsModel::Overwrite_KeepBoth);
536 ui->radioButtonOverwriteModeSkipFile->setChecked(m_settings->overwriteMode() == SettingsModel::Overwrite_SkipFile);
537 ui->radioButtonOverwriteModeReplaces->setChecked(m_settings->overwriteMode() == SettingsModel::Overwrite_Replaces);
539 FileExtsModel *fileExtModel = new FileExtsModel(this);
540 fileExtModel->importItems(m_settings->renameFiles_fileExtension());
541 ui->tableViewFileExts->setModel(fileExtModel);
542 ui->tableViewFileExts->verticalHeader() ->setResizeMode(QHeaderView::ResizeToContents);
543 ui->tableViewFileExts->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
545 connect(ui->sliderLameAlgoQuality, SIGNAL(valueChanged(int)), this, SLOT(updateLameAlgoQuality(int)));
546 connect(ui->checkBoxBitrateManagement, SIGNAL(clicked(bool)), this, SLOT(bitrateManagementEnabledChanged(bool)));
547 connect(ui->spinBoxBitrateManagementMin, SIGNAL(valueChanged(int)), this, SLOT(bitrateManagementMinChanged(int)));
548 connect(ui->spinBoxBitrateManagementMax, SIGNAL(valueChanged(int)), this, SLOT(bitrateManagementMaxChanged(int)));
549 connect(ui->comboBoxMP3ChannelMode, SIGNAL(currentIndexChanged(int)), this, SLOT(channelModeChanged(int)));
550 connect(ui->comboBoxSamplingRate, SIGNAL(currentIndexChanged(int)), this, SLOT(samplingRateChanged(int)));
551 connect(ui->checkBoxNeroAAC2PassMode, SIGNAL(clicked(bool)), this, SLOT(neroAAC2PassChanged(bool)));
552 connect(ui->comboBoxAACProfile, SIGNAL(currentIndexChanged(int)), this, SLOT(neroAACProfileChanged(int)));
553 connect(ui->checkBoxNormalizationFilterEnabled, SIGNAL(clicked(bool)), this, SLOT(normalizationEnabledChanged(bool)));
554 connect(ui->checkBoxNormalizationFilterDynamic, SIGNAL(clicked(bool)), this, SLOT(normalizationDynamicChanged(bool)));
555 connect(ui->checkBoxNormalizationFilterCoupled, SIGNAL(clicked(bool)), this, SLOT(normalizationCoupledChanged(bool)));
556 connect(ui->comboBoxAftenCodingMode, SIGNAL(currentIndexChanged(int)), this, SLOT(aftenCodingModeChanged(int)));
557 connect(ui->comboBoxAftenDRCMode, SIGNAL(currentIndexChanged(int)), this, SLOT(aftenDRCModeChanged(int)));
558 connect(ui->spinBoxAftenSearchSize, SIGNAL(valueChanged(int)), this, SLOT(aftenSearchSizeChanged(int)));
559 connect(ui->checkBoxAftenFastAllocation, SIGNAL(clicked(bool)), this, SLOT(aftenFastAllocationChanged(bool)));
560 connect(ui->spinBoxNormalizationFilterPeak, SIGNAL(valueChanged(double)), this, SLOT(normalizationMaxVolumeChanged(double)));
561 connect(ui->spinBoxNormalizationFilterSize, SIGNAL(valueChanged(int)), this, SLOT(normalizationFilterSizeChanged(int)));
562 connect(ui->spinBoxNormalizationFilterSize, SIGNAL(editingFinished()), this, SLOT(normalizationFilterSizeFinished()));
563 connect(ui->spinBoxToneAdjustBass, SIGNAL(valueChanged(double)), this, SLOT(toneAdjustBassChanged(double)));
564 connect(ui->spinBoxToneAdjustTreble, SIGNAL(valueChanged(double)), this, SLOT(toneAdjustTrebleChanged(double)));
565 connect(ui->buttonToneAdjustReset, SIGNAL(clicked()), this, SLOT(toneAdjustTrebleReset()));
566 connect(ui->lineEditCustomParamLAME, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
567 connect(ui->lineEditCustomParamOggEnc, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
568 connect(ui->lineEditCustomParamNeroAAC, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
569 connect(ui->lineEditCustomParamFLAC, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
570 connect(ui->lineEditCustomParamAften, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
571 connect(ui->lineEditCustomParamOpus, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
572 connect(ui->sliderMaxInstances, SIGNAL(valueChanged(int)), this, SLOT(updateMaximumInstances(int)));
573 connect(ui->checkBoxAutoDetectInstances, SIGNAL(clicked(bool)), this, SLOT(autoDetectInstancesChanged(bool)));
574 connect(ui->buttonBrowseCustomTempFolder, SIGNAL(clicked()), this, SLOT(browseCustomTempFolderButtonClicked()));
575 connect(ui->lineEditCustomTempFolder, SIGNAL(textChanged(QString)), this, SLOT(customTempFolderChanged(QString)));
576 connect(ui->checkBoxUseSystemTempFolder, SIGNAL(clicked(bool)), this, SLOT(useCustomTempFolderChanged(bool)));
577 connect(ui->buttonResetAdvancedOptions, SIGNAL(clicked()), this, SLOT(resetAdvancedOptionsButtonClicked()));
578 connect(ui->checkBoxRename_Rename, SIGNAL(clicked(bool)), this, SLOT(renameOutputEnabledChanged(bool)));
579 connect(ui->checkBoxRename_RegExp, SIGNAL(clicked(bool)), this, SLOT(renameRegExpEnabledChanged(bool)));
580 connect(ui->lineEditRenamePattern, SIGNAL(editingFinished()), this, SLOT(renameOutputPatternChanged()));
581 connect(ui->lineEditRenamePattern, SIGNAL(textChanged(QString)), this, SLOT(renameOutputPatternChanged(QString)));
582 connect(ui->lineEditRenameRegExp_Search, SIGNAL(editingFinished()), this, SLOT(renameRegExpValueChanged()));
583 connect(ui->lineEditRenameRegExp_Search, SIGNAL(textChanged(QString)), this, SLOT(renameRegExpSearchChanged(QString)));
584 connect(ui->lineEditRenameRegExp_Replace, SIGNAL(editingFinished()), this, SLOT(renameRegExpValueChanged()));
585 connect(ui->lineEditRenameRegExp_Replace, SIGNAL(textChanged(QString)), this, SLOT(renameRegExpReplaceChanged(QString)));
586 connect(ui->labelShowRenameMacros, SIGNAL(linkActivated(QString)), this, SLOT(showRenameMacros(QString)));
587 connect(ui->labelShowRegExpHelp, SIGNAL(linkActivated(QString)), this, SLOT(showRenameMacros(QString)));
588 connect(ui->checkBoxForceStereoDownmix, SIGNAL(clicked(bool)), this, SLOT(forceStereoDownmixEnabledChanged(bool)));
589 connect(ui->comboBoxOpusFramesize, SIGNAL(currentIndexChanged(int)), this, SLOT(opusSettingsChanged()));
590 connect(ui->spinBoxOpusComplexity, SIGNAL(valueChanged(int)), this, SLOT(opusSettingsChanged()));
591 connect(ui->checkBoxOpusDisableResample, SIGNAL(clicked(bool)), this, SLOT(opusSettingsChanged()));
592 connect(ui->buttonRename_Rename, SIGNAL(clicked(bool)), this, SLOT(renameButtonClicked(bool)));
593 connect(ui->buttonRename_RegExp, SIGNAL(clicked(bool)), this, SLOT(renameButtonClicked(bool)));
594 connect(ui->buttonRename_FileEx, SIGNAL(clicked(bool)), this, SLOT(renameButtonClicked(bool)));
595 connect(ui->buttonFileExts_Add, SIGNAL(clicked()), this, SLOT(fileExtAddButtonClicked()));
596 connect(ui->buttonFileExts_Remove, SIGNAL(clicked()), this, SLOT(fileExtRemoveButtonClicked()));
597 connect(ui->checkBoxKeepOriginalDateTime, SIGNAL(clicked(bool)), this, SLOT(keepOriginalDateTimeChanged(bool)));
598 connect(m_overwriteButtonGroup.data(), SIGNAL(buttonClicked(int)), this, SLOT(overwriteModeChanged(int)));
599 connect(m_evenFilterCustumParamsHelp.data(), SIGNAL(eventOccurred(QWidget*, QEvent*)), this, SLOT(customParamsHelpRequested(QWidget*, QEvent*)));
600 connect(fileExtModel, SIGNAL(modelReset()), this, SLOT(fileExtModelChanged()));
602 //--------------------------------
603 // Force initial GUI update
604 //--------------------------------
606 updateLameAlgoQuality(ui->sliderLameAlgoQuality->value());
607 updateMaximumInstances(ui->sliderMaxInstances->value());
608 toneAdjustTrebleChanged(ui->spinBoxToneAdjustTreble->value());
609 toneAdjustBassChanged(ui->spinBoxToneAdjustBass->value());
610 normalizationEnabledChanged(ui->checkBoxNormalizationFilterEnabled->isChecked());
611 customParamsChanged();
613 //--------------------------------
614 // Initialize actions
615 //--------------------------------
617 //Activate file menu actions
618 ui->actionOpenFolder ->setData(QVariant::fromValue<bool>(false));
619 ui->actionOpenFolderRecursively->setData(QVariant::fromValue<bool>(true));
620 connect(ui->actionOpenFolder, SIGNAL(triggered()), this, SLOT(openFolderActionActivated()));
621 connect(ui->actionOpenFolderRecursively, SIGNAL(triggered()), this, SLOT(openFolderActionActivated()));
623 //Activate view menu actions
624 m_tabActionGroup.reset(new QActionGroup(this));
625 m_tabActionGroup->addAction(ui->actionSourceFiles);
626 m_tabActionGroup->addAction(ui->actionOutputDirectory);
627 m_tabActionGroup->addAction(ui->actionCompression);
628 m_tabActionGroup->addAction(ui->actionMetaData);
629 m_tabActionGroup->addAction(ui->actionAdvancedOptions);
630 ui->actionSourceFiles->setData(0);
631 ui->actionOutputDirectory->setData(1);
632 ui->actionMetaData->setData(2);
633 ui->actionCompression->setData(3);
634 ui->actionAdvancedOptions->setData(4);
635 ui->actionSourceFiles->setChecked(true);
636 connect(m_tabActionGroup.data(), SIGNAL(triggered(QAction*)), this, SLOT(tabActionActivated(QAction*)));
638 //Activate style menu actions
639 m_styleActionGroup .reset(new QActionGroup(this));
640 m_styleActionGroup->addAction(ui->actionStylePlastique);
641 m_styleActionGroup->addAction(ui->actionStyleCleanlooks);
642 m_styleActionGroup->addAction(ui->actionStyleWindowsVista);
643 m_styleActionGroup->addAction(ui->actionStyleWindowsXP);
644 m_styleActionGroup->addAction(ui->actionStyleWindowsClassic);
645 ui->actionStylePlastique->setData(0);
646 ui->actionStyleCleanlooks->setData(1);
647 ui->actionStyleWindowsVista->setData(2);
648 ui->actionStyleWindowsXP->setData(3);
649 ui->actionStyleWindowsClassic->setData(4);
650 ui->actionStylePlastique->setChecked(true);
651 ui->actionStyleWindowsXP->setEnabled((QSysInfo::windowsVersion() & QSysInfo::WV_NT_based) >= QSysInfo::WV_XP && MUtils::GUI::themes_enabled());
652 ui->actionStyleWindowsVista->setEnabled((QSysInfo::windowsVersion() & QSysInfo::WV_NT_based) >= QSysInfo::WV_VISTA && MUtils::GUI::themes_enabled());
653 connect(m_styleActionGroup.data(), SIGNAL(triggered(QAction*)), this, SLOT(styleActionActivated(QAction*)));
654 styleActionActivated(NULL);
656 //Populate the language menu
657 m_languageActionGroup.reset(new QActionGroup(this));
658 QStringList translations;
659 if(MUtils::Translation::enumerate(translations) > 0)
661 for(QStringList::ConstIterator iter = translations.constBegin(); iter != translations.constEnd(); iter++)
663 QAction *currentLanguage = new QAction(this);
664 currentLanguage->setData(*iter);
665 currentLanguage->setText(MUtils::Translation::get_name(*iter));
666 currentLanguage->setIcon(QIcon(QString(":/flags/%1.png").arg(*iter)));
667 currentLanguage->setCheckable(true);
668 currentLanguage->setChecked(false);
669 m_languageActionGroup->addAction(currentLanguage);
670 ui->menuLanguage->insertAction(ui->actionLoadTranslationFromFile, currentLanguage);
673 ui->menuLanguage->insertSeparator(ui->actionLoadTranslationFromFile);
674 connect(ui->actionLoadTranslationFromFile, SIGNAL(triggered(bool)), this, SLOT(languageFromFileActionActivated(bool)));
675 connect(m_languageActionGroup.data(), SIGNAL(triggered(QAction*)), this, SLOT(languageActionActivated(QAction*)));
676 ui->actionLoadTranslationFromFile->setChecked(false);
678 //Activate tools menu actions
679 ui->actionDisableUpdateReminder->setChecked(!m_settings->autoUpdateEnabled());
680 ui->actionDisableSounds->setChecked(!m_settings->soundsEnabled());
681 ui->actionDisableNeroAacNotifications->setChecked(!m_settings->neroAacNotificationsEnabled());
682 ui->actionDisableSlowStartupNotifications->setChecked(!m_settings->antivirNotificationsEnabled());
683 ui->actionDisableShellIntegration->setChecked(!m_settings->shellIntegrationEnabled());
684 ui->actionDisableShellIntegration->setDisabled(lamexp_version_portable() && ui->actionDisableShellIntegration->isChecked());
685 ui->actionCheckForBetaUpdates->setChecked(m_settings->autoUpdateCheckBeta() || lamexp_version_demo());
686 ui->actionCheckForBetaUpdates->setEnabled(!lamexp_version_demo());
687 ui->actionHibernateComputer->setChecked(m_settings->hibernateComputer());
688 ui->actionHibernateComputer->setEnabled(MUtils::OS::is_hibernation_supported());
689 connect(ui->actionDisableUpdateReminder, SIGNAL(triggered(bool)), this, SLOT(disableUpdateReminderActionTriggered(bool)));
690 connect(ui->actionDisableSounds, SIGNAL(triggered(bool)), this, SLOT(disableSoundsActionTriggered(bool)));
691 connect(ui->actionDisableNeroAacNotifications, SIGNAL(triggered(bool)), this, SLOT(disableNeroAacNotificationsActionTriggered(bool)));
692 connect(ui->actionDisableSlowStartupNotifications, SIGNAL(triggered(bool)), this, SLOT(disableSlowStartupNotificationsActionTriggered(bool)));
693 connect(ui->actionDisableShellIntegration, SIGNAL(triggered(bool)), this, SLOT(disableShellIntegrationActionTriggered(bool)));
694 connect(ui->actionShowDropBoxWidget, SIGNAL(triggered(bool)), this, SLOT(showDropBoxWidgetActionTriggered(bool)));
695 connect(ui->actionHibernateComputer, SIGNAL(triggered(bool)), this, SLOT(hibernateComputerActionTriggered(bool)));
696 connect(ui->actionCheckForBetaUpdates, SIGNAL(triggered(bool)), this, SLOT(checkForBetaUpdatesActionTriggered(bool)));
697 connect(ui->actionImportCueSheet, SIGNAL(triggered(bool)), this, SLOT(importCueSheetActionTriggered(bool)));
699 //Activate help menu actions
700 ui->actionVisitHomepage ->setData(QString::fromLatin1(lamexp_website_url()));
701 ui->actionVisitSupport ->setData(QString::fromLatin1(lamexp_support_url()));
702 ui->actionVisitMuldersSite ->setData(QString::fromLatin1(lamexp_mulders_url()));
703 ui->actionVisitTracker ->setData(QString::fromLatin1(lamexp_tracker_url()));
704 ui->actionVisitHAK ->setData(QString::fromLatin1(g_hydrogen_audio_url));
705 ui->actionDocumentManual ->setData(QString("%1/Manual.html") .arg(QApplication::applicationDirPath()));
706 ui->actionDocumentChangelog->setData(QString("%1/Changelog.html").arg(QApplication::applicationDirPath()));
707 ui->actionDocumentTranslate->setData(QString("%1/Translate.html").arg(QApplication::applicationDirPath()));
708 connect(ui->actionCheckUpdates, SIGNAL(triggered()), this, SLOT(checkUpdatesActionActivated()));
709 connect(ui->actionVisitSupport, SIGNAL(triggered()), this, SLOT(visitHomepageActionActivated()));
710 connect(ui->actionVisitTracker, SIGNAL(triggered()), this, SLOT(visitHomepageActionActivated()));
711 connect(ui->actionVisitHomepage, SIGNAL(triggered()), this, SLOT(visitHomepageActionActivated()));
712 connect(ui->actionVisitMuldersSite, SIGNAL(triggered()), this, SLOT(visitHomepageActionActivated()));
713 connect(ui->actionVisitHAK, SIGNAL(triggered()), this, SLOT(visitHomepageActionActivated()));
714 connect(ui->actionDocumentManual, SIGNAL(triggered()), this, SLOT(documentActionActivated()));
715 connect(ui->actionDocumentChangelog, SIGNAL(triggered()), this, SLOT(documentActionActivated()));
716 connect(ui->actionDocumentTranslate, SIGNAL(triggered()), this, SLOT(documentActionActivated()));
718 //--------------------------------
719 // Prepare to show window
720 //--------------------------------
722 //Center window in screen
723 QRect desktopRect = QApplication::desktop()->screenGeometry();
724 QRect thisRect = this->geometry();
725 move((desktopRect.width() - thisRect.width()) / 2, (desktopRect.height() - thisRect.height()) / 2);
726 setMinimumSize(thisRect.width(), thisRect.height());
728 //Create DropBox widget
729 m_dropBox.reset(new DropBox(this, m_fileListModel, m_settings));
730 connect(m_fileListModel, SIGNAL(modelReset()), m_dropBox.data(), SLOT(modelChanged()));
731 connect(m_fileListModel, SIGNAL(rowsInserted(QModelIndex,int,int)), m_dropBox.data(), SLOT(modelChanged()));
732 connect(m_fileListModel, SIGNAL(rowsRemoved(QModelIndex,int,int)), m_dropBox.data(), SLOT(modelChanged()));
733 connect(m_fileListModel, SIGNAL(rowAppended()), m_dropBox.data(), SLOT(modelChanged()));
735 //Create message handler thread
736 m_messageHandler.reset(new MessageHandlerThread(ipcChannel));
737 connect(m_messageHandler.data(), SIGNAL(otherInstanceDetected()), this, SLOT(notifyOtherInstance()), Qt::QueuedConnection);
738 connect(m_messageHandler.data(), SIGNAL(fileReceived(QString)), this, SLOT(addFileDelayed(QString)), Qt::QueuedConnection);
739 connect(m_messageHandler.data(), SIGNAL(folderReceived(QString, bool)), this, SLOT(addFolderDelayed(QString, bool)), Qt::QueuedConnection);
740 connect(m_messageHandler.data(), SIGNAL(killSignalReceived()), this, SLOT(close()), Qt::QueuedConnection);
741 m_messageHandler->start();
743 //Init delayed file handling
744 m_delayedFileList .reset(new QStringList());
745 m_delayedFileTimer.reset(new QTimer());
746 m_delayedFileTimer->setSingleShot(true);
747 m_delayedFileTimer->setInterval(5000);
748 connect(m_delayedFileTimer.data(), SIGNAL(timeout()), this, SLOT(handleDelayedFiles()));
750 //Load translation
751 initializeTranslation();
753 //Re-translate (make sure we translate once)
754 QEvent languageChangeEvent(QEvent::LanguageChange);
755 changeEvent(&languageChangeEvent);
757 //Enable Drag & Drop
758 m_droppedFileList.reset(new QList<QUrl>());
759 this->setAcceptDrops(true);
762 ////////////////////////////////////////////////////////////
763 // Destructor
764 ////////////////////////////////////////////////////////////
766 MainWindow::~MainWindow(void)
768 //Stop message handler thread
769 if(m_messageHandler && m_messageHandler->isRunning())
771 m_messageHandler->stop();
772 if(!m_messageHandler->wait(2500))
774 m_messageHandler->terminate();
775 m_messageHandler->wait();
779 //Unset models
780 SET_MODEL(ui->sourceFileView, NULL);
781 SET_MODEL(ui->outputFolderView, NULL);
782 SET_MODEL(ui->metaDataView, NULL);
784 //Un-initialize the dialog
785 MUTILS_DELETE(ui);
788 ////////////////////////////////////////////////////////////
789 // PRIVATE FUNCTIONS
790 ////////////////////////////////////////////////////////////
793 * Add file to source list
795 void MainWindow::addFiles(const QStringList &files)
797 if(files.isEmpty())
799 return;
802 if(ui->tabWidget->currentIndex() != 0)
804 SignalBlockHelper signalBlockHelper(ui->tabWidget);
805 ui->tabWidget->setCurrentIndex(0);
806 tabPageChanged(ui->tabWidget->currentIndex(), true);
809 INIT_BANNER();
810 QScopedPointer<FileAnalyzer> analyzer(new FileAnalyzer(files));
812 connect(analyzer.data(), SIGNAL(fileSelected(QString)), m_banner.data(), SLOT(setText(QString)), Qt::QueuedConnection);
813 connect(analyzer.data(), SIGNAL(progressValChanged(unsigned int)), m_banner.data(), SLOT(setProgressVal(unsigned int)), Qt::QueuedConnection);
814 connect(analyzer.data(), SIGNAL(progressMaxChanged(unsigned int)), m_banner.data(), SLOT(setProgressMax(unsigned int)), Qt::QueuedConnection);
815 connect(analyzer.data(), SIGNAL(fileAnalyzed(AudioFileModel)), m_fileListModel, SLOT(addFile(AudioFileModel)), Qt::QueuedConnection);
816 connect(m_banner.data(), SIGNAL(userAbort()), analyzer.data(), SLOT(abortProcess()), Qt::DirectConnection);
818 if(!analyzer.isNull())
820 FileListBlockHelper fileListBlocker(m_fileListModel);
821 m_banner->show(tr("Adding file(s), please wait..."), analyzer.data());
824 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
825 ui->sourceFileView->update();
826 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
827 ui->sourceFileView->scrollToBottom();
828 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
830 if(analyzer->filesDenied())
832 QMessageBox::warning(this, tr("Access Denied"), QString("%1<br>%2").arg(NOBR(tr("%n file(s) have been rejected, because read access was not granted!", "", analyzer->filesDenied())), NOBR(tr("This usually means the file is locked by another process."))));
834 if(analyzer->filesDummyCDDA())
836 QMessageBox::warning(this, tr("CDDA Files"), QString("%1<br><br>%2<br>%3").arg(NOBR(tr("%n file(s) have been rejected, because they are dummy CDDA files!", "", analyzer->filesDummyCDDA())), NOBR(tr("Sorry, LameXP cannot extract audio tracks from an Audio-CD at present.")), NOBR(tr("We recommend using %1 for that purpose.").arg("<a href=\"http://www.exactaudiocopy.de/\">Exact Audio Copy</a>"))));
838 if(analyzer->filesCueSheet())
840 QMessageBox::warning(this, tr("Cue Sheet"), QString("%1<br>%2").arg(NOBR(tr("%n file(s) have been rejected, because they appear to be Cue Sheet images!", "",analyzer->filesCueSheet())), NOBR(tr("Please use LameXP's Cue Sheet wizard for importing Cue Sheet files."))));
842 if(analyzer->filesRejected())
844 QMessageBox::warning(this, tr("Files Rejected"), QString("%1<br>%2").arg(NOBR(tr("%n file(s) have been rejected, because the file format could not be recognized!", "", analyzer->filesRejected())), NOBR(tr("This usually means the file is damaged or the file format is not supported."))));
847 m_banner->close();
851 * Add folder to source list
853 void MainWindow::addFolder(const QString &path, bool recursive, bool delayed, QString filter)
855 QFileInfoList folderInfoList;
856 folderInfoList << QFileInfo(path);
857 QStringList fileList;
859 showBanner(tr("Scanning folder(s) for files, please wait..."));
861 QApplication::processEvents();
862 MUtils::OS::check_key_state_esc();
864 while(!folderInfoList.isEmpty())
866 if(MUtils::OS::check_key_state_esc())
868 qWarning("Operation cancelled by user!");
869 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
870 fileList.clear();
871 break;
874 QDir currentDir(folderInfoList.takeFirst().canonicalFilePath());
875 QFileInfoList fileInfoList = currentDir.entryInfoList(QDir::Files | QDir::NoSymLinks);
877 for(QFileInfoList::ConstIterator iter = fileInfoList.constBegin(); iter != fileInfoList.constEnd(); iter++)
879 if(filter.isEmpty() || (iter->suffix().compare(filter, Qt::CaseInsensitive) == 0))
881 fileList << iter->canonicalFilePath();
885 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
887 if(recursive)
889 folderInfoList.append(currentDir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks));
890 QApplication::processEvents();
894 m_banner->close();
895 QApplication::processEvents();
897 if(!fileList.isEmpty())
899 if(delayed)
901 addFilesDelayed(fileList);
903 else
905 addFiles(fileList);
911 * Check for updates
913 bool MainWindow::checkForUpdates(void)
915 bool bReadyToInstall = false;
917 UpdateDialog *updateDialog = new UpdateDialog(m_settings, this);
918 updateDialog->exec();
920 if(updateDialog->getSuccess())
922 SHOW_CORNER_WIDGET(false);
923 m_settings->autoUpdateLastCheck(QDate::currentDate().toString(Qt::ISODate));
924 bReadyToInstall = updateDialog->updateReadyToInstall();
927 MUTILS_DELETE(updateDialog);
928 return bReadyToInstall;
932 * Refresh list of favorites
934 void MainWindow::refreshFavorites(void)
936 QList<QAction*> folderList = m_outputFolderFavoritesMenu->actions();
937 QStringList favorites = m_settings->favoriteOutputFolders().split("|", QString::SkipEmptyParts);
938 while(favorites.count() > 6) favorites.removeFirst();
940 while(!folderList.isEmpty())
942 QAction *currentItem = folderList.takeFirst();
943 if(currentItem->isSeparator()) break;
944 m_outputFolderFavoritesMenu->removeAction(currentItem);
945 MUTILS_DELETE(currentItem);
948 QAction *lastItem = m_outputFolderFavoritesMenu->actions().first();
950 while(!favorites.isEmpty())
952 QString path = favorites.takeLast();
953 if(QDir(path).exists())
955 QAction *action = new QAction(QIcon(":/icons/folder_go.png"), QDir::toNativeSeparators(path), this);
956 action->setData(path);
957 m_outputFolderFavoritesMenu->insertAction(lastItem, action);
958 connect(action, SIGNAL(triggered(bool)), this, SLOT(gotoFavoriteFolder()));
959 lastItem = action;
965 * Initilaize translation
967 void MainWindow::initializeTranslation(void)
969 bool translationLoaded = false;
971 //Try to load "external" translation file
972 if(!m_settings->currentLanguageFile().isEmpty())
974 const QString qmFilePath = QFileInfo(m_settings->currentLanguageFile()).canonicalFilePath();
975 if((!qmFilePath.isEmpty()) && QFileInfo(qmFilePath).exists() && QFileInfo(qmFilePath).isFile() && (QFileInfo(qmFilePath).suffix().compare("qm", Qt::CaseInsensitive) == 0))
977 if(MUtils::Translation::install_translator_from_file(qmFilePath))
979 QList<QAction*> actions = m_languageActionGroup->actions();
980 while(!actions.isEmpty()) actions.takeFirst()->setChecked(false);
981 ui->actionLoadTranslationFromFile->setChecked(true);
982 translationLoaded = true;
987 //Try to load "built-in" translation file
988 if(!translationLoaded)
990 QList<QAction*> languageActions = m_languageActionGroup->actions();
991 while(!languageActions.isEmpty())
993 QAction *currentLanguage = languageActions.takeFirst();
994 if(currentLanguage->data().toString().compare(m_settings->currentLanguage(), Qt::CaseInsensitive) == 0)
996 currentLanguage->setChecked(true);
997 languageActionActivated(currentLanguage);
998 translationLoaded = true;
1003 //Fallback to default translation
1004 if(!translationLoaded)
1006 QList<QAction*> languageActions = m_languageActionGroup->actions();
1007 while(!languageActions.isEmpty())
1009 QAction *currentLanguage = languageActions.takeFirst();
1010 if(currentLanguage->data().toString().compare(MUtils::Translation::DEFAULT_LANGID, Qt::CaseInsensitive) == 0)
1012 currentLanguage->setChecked(true);
1013 languageActionActivated(currentLanguage);
1014 translationLoaded = true;
1019 //Make sure we loaded some translation
1020 if(!translationLoaded)
1022 qFatal("Failed to load any translation, this is NOT supposed to happen!");
1027 * Open a document link
1029 void MainWindow::openDocumentLink(QAction *const action)
1031 if(!(action->data().isValid() && (action->data().type() == QVariant::String)))
1033 qWarning("Cannot open document for this QAction!");
1034 return;
1037 //Try to open exitsing document file
1038 const QFileInfo document(action->data().toString());
1039 if(document.exists() && document.isFile() && (document.size() >= 1024))
1041 QDesktopServices::openUrl(QUrl::fromLocalFile(document.canonicalFilePath()));
1042 return;
1045 //Document not found -> fallback mode!
1046 qWarning("Document '%s' not found -> redirecting to the website!", MUTILS_UTF8(document.fileName()));
1047 const QUrl url(QString("%1/%2").arg(QString::fromLatin1(g_documents_base_url), document.fileName()));
1048 QDesktopServices::openUrl(url);
1052 * Move selected files up/down
1054 void MainWindow::moveSelectedFiles(const bool &up)
1056 QItemSelectionModel *const selection = ui->sourceFileView->selectionModel();
1057 if(selection && selection->hasSelection())
1059 const QModelIndexList selectedRows = up ? selection->selectedRows() : INVERT_LIST(selection->selectedRows());
1060 if((up && (selectedRows.first().row() > 0)) || ((!up) && (selectedRows.first().row() < m_fileListModel->rowCount() - 1)))
1062 const int delta = up ? (-1) : 1;
1063 const int firstIndex = (up ? selectedRows.first() : selectedRows.last()).row() + delta;
1064 const int selectionCount = selectedRows.count();
1065 if(abs(delta) > 0)
1067 FileListBlockHelper fileListBlocker(m_fileListModel);
1068 for(QModelIndexList::ConstIterator iter = selectedRows.constBegin(); iter != selectedRows.constEnd(); iter++)
1070 if(!m_fileListModel->moveFile((*iter), delta))
1072 break;
1076 selection->clearSelection();
1077 for(int i = 0; i < selectionCount; i++)
1079 const QModelIndex item = m_fileListModel->index(firstIndex + i, 0);
1080 selection->select(QItemSelection(item, item), QItemSelectionModel::Select | QItemSelectionModel::Rows);
1082 ui->sourceFileView->scrollTo(m_fileListModel->index((up ? firstIndex : firstIndex + selectionCount - 1), 0), QAbstractItemView::PositionAtCenter);
1083 return;
1086 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN);
1090 * Show banner popup dialog
1092 void MainWindow::showBanner(const QString &text)
1094 INIT_BANNER();
1095 m_banner->show(text);
1099 * Show banner popup dialog
1101 void MainWindow::showBanner(const QString &text, QThread *const thread)
1103 INIT_BANNER();
1104 m_banner->show(text, thread);
1108 * Show banner popup dialog
1110 void MainWindow::showBanner(const QString &text, QEventLoop *const eventLoop)
1112 INIT_BANNER();
1113 m_banner->show(text, eventLoop);
1117 * Show banner popup dialog
1119 void MainWindow::showBanner(const QString &text, bool &flag, const bool &test)
1121 if((!flag) && (test))
1123 INIT_BANNER();
1124 m_banner->show(text);
1125 flag = true;
1129 ////////////////////////////////////////////////////////////
1130 // EVENTS
1131 ////////////////////////////////////////////////////////////
1134 * Window is about to be shown
1136 void MainWindow::showEvent(QShowEvent *event)
1138 m_accepted = false;
1139 resizeEvent(NULL);
1140 sourceModelChanged();
1142 if(!event->spontaneous())
1144 SignalBlockHelper signalBlockHelper(ui->tabWidget);
1145 ui->tabWidget->setCurrentIndex(0);
1146 tabPageChanged(ui->tabWidget->currentIndex(), true);
1149 if(m_firstTimeShown)
1151 m_firstTimeShown = false;
1152 QTimer::singleShot(0, this, SLOT(windowShown()));
1154 else
1156 if(m_settings->dropBoxWidgetEnabled())
1158 m_dropBox->setVisible(true);
1164 * Re-translate the UI
1166 void MainWindow::changeEvent(QEvent *e)
1168 QMainWindow::changeEvent(e);
1169 if(e->type() != QEvent::LanguageChange)
1171 return;
1174 int comboBoxIndex[6];
1176 //Backup combobox indices, as retranslateUi() resets
1177 comboBoxIndex[0] = ui->comboBoxMP3ChannelMode->currentIndex();
1178 comboBoxIndex[1] = ui->comboBoxSamplingRate->currentIndex();
1179 comboBoxIndex[2] = ui->comboBoxAACProfile->currentIndex();
1180 comboBoxIndex[3] = ui->comboBoxAftenCodingMode->currentIndex();
1181 comboBoxIndex[4] = ui->comboBoxAftenDRCMode->currentIndex();
1182 comboBoxIndex[5] = ui->comboBoxOpusFramesize->currentIndex();
1184 //Re-translate from UIC
1185 ui->retranslateUi(this);
1187 //Restore combobox indices
1188 ui->comboBoxMP3ChannelMode->setCurrentIndex(comboBoxIndex[0]);
1189 ui->comboBoxSamplingRate->setCurrentIndex(comboBoxIndex[1]);
1190 ui->comboBoxAACProfile->setCurrentIndex(comboBoxIndex[2]);
1191 ui->comboBoxAftenCodingMode->setCurrentIndex(comboBoxIndex[3]);
1192 ui->comboBoxAftenDRCMode->setCurrentIndex(comboBoxIndex[4]);
1193 ui->comboBoxOpusFramesize->setCurrentIndex(comboBoxIndex[5]);
1195 //Update the window title
1196 if(MUTILS_DEBUG)
1198 setWindowTitle(QString("%1 [!!! DEBUG BUILD !!!]").arg(windowTitle()));
1200 else if(lamexp_version_demo())
1202 setWindowTitle(QString("%1 [%2]").arg(windowTitle(), tr("DEMO VERSION")));
1205 //Manually re-translate widgets that UIC doesn't handle
1206 m_outputFolderNoteBox->setText(tr("Initializing directory outline, please be patient..."));
1207 m_dropNoteLabel->setText(QString("<br><img src=\":/images/DropZone.png\"><br><br>%1").arg(tr("You can drop in audio files here!")));
1208 if(QLabel *cornerWidget = dynamic_cast<QLabel*>(ui->menubar->cornerWidget()))
1210 cornerWidget->setText(QString("<nobr><img src=\":/icons/exclamation_small.png\">&nbsp;<b style=\"color:darkred\">%1</b>&nbsp;&nbsp;&nbsp;</nobr>").arg(tr("Check for Updates")));
1212 m_showDetailsContextAction->setText(tr("Show Details"));
1213 m_previewContextAction->setText(tr("Open File in External Application"));
1214 m_findFileContextAction->setText(tr("Browse File Location"));
1215 m_showFolderContextAction->setText(tr("Browse Selected Folder"));
1216 m_refreshFolderContextAction->setText(tr("Refresh Directory Outline"));
1217 m_goUpFolderContextAction->setText(tr("Go To Parent Directory"));
1218 m_addFavoriteFolderAction->setText(tr("Bookmark Current Output Folder"));
1219 m_exportCsvContextAction->setText(tr("Export Meta Tags to CSV File"));
1220 m_importCsvContextAction->setText(tr("Import Meta Tags from CSV File"));
1222 //Force GUI update
1223 m_metaInfoModel->clearData();
1224 m_metaInfoModel->setData(m_metaInfoModel->index(4, 1), m_settings->metaInfoPosition());
1225 updateEncoder(m_settings->compressionEncoder());
1226 updateLameAlgoQuality(ui->sliderLameAlgoQuality->value());
1227 updateMaximumInstances(ui->sliderMaxInstances->value());
1228 renameOutputPatternChanged(ui->lineEditRenamePattern->text(), true);
1229 renameRegExpSearchChanged (ui->lineEditRenameRegExp_Search ->text(), true);
1230 renameRegExpReplaceChanged(ui->lineEditRenameRegExp_Replace->text(), true);
1232 //Re-install shell integration
1233 if(m_settings->shellIntegrationEnabled())
1235 ShellIntegration::install();
1238 //Translate system menu
1239 MUtils::GUI::sysmenu_update(this, IDM_ABOUTBOX, ui->buttonAbout->text());
1241 //Force resize event
1242 QApplication::postEvent(this, new QResizeEvent(this->size(), QSize()));
1243 for(QObjectList::ConstIterator iter = this->children().constBegin(); iter != this->children().constEnd(); iter++)
1245 if(QWidget *child = dynamic_cast<QWidget*>(*iter))
1247 QApplication::postEvent(child, new QResizeEvent(child->size(), QSize()));
1251 //Force tabe page change
1252 tabPageChanged(ui->tabWidget->currentIndex(), true);
1256 * File dragged over window
1258 void MainWindow::dragEnterEvent(QDragEnterEvent *event)
1260 QStringList formats = event->mimeData()->formats();
1262 if(formats.contains("application/x-qt-windows-mime;value=\"FileNameW\"", Qt::CaseInsensitive) && formats.contains("text/uri-list", Qt::CaseInsensitive))
1264 event->acceptProposedAction();
1269 * File dropped onto window
1271 void MainWindow::dropEvent(QDropEvent *event)
1273 m_droppedFileList->clear();
1274 (*m_droppedFileList) << event->mimeData()->urls();
1275 if(!m_droppedFileList->isEmpty())
1277 PLAY_SOUND_OPTIONAL("drop", true);
1278 QTimer::singleShot(0, this, SLOT(handleDroppedFiles()));
1283 * Window tries to close
1285 void MainWindow::closeEvent(QCloseEvent *event)
1287 if(BANNER_VISIBLE || m_delayedFileTimer->isActive())
1289 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN);
1290 event->ignore();
1293 if(m_dropBox)
1295 m_dropBox->hide();
1300 * Window was resized
1302 void MainWindow::resizeEvent(QResizeEvent *event)
1304 if(event) QMainWindow::resizeEvent(event);
1306 if(QWidget *port = ui->sourceFileView->viewport())
1308 m_dropNoteLabel->setGeometry(port->geometry());
1311 if(QWidget *port = ui->outputFolderView->viewport())
1313 m_outputFolderNoteBox->setGeometry(16, (port->height() - 64) / 2, port->width() - 32, 64);
1318 * Key press event filter
1320 void MainWindow::keyPressEvent(QKeyEvent *e)
1322 if(e->key() == Qt::Key_Delete)
1324 if(ui->sourceFileView->isVisible())
1326 QTimer::singleShot(0, this, SLOT(removeFileButtonClicked()));
1327 return;
1331 if(e->modifiers().testFlag(Qt::ControlModifier) && (e->key() == Qt::Key_F5))
1333 initializeTranslation();
1334 MUtils::Sound::beep(MUtils::Sound::BEEP_NFO);
1335 return;
1338 if(e->key() == Qt::Key_F5)
1340 if(ui->outputFolderView->isVisible())
1342 QTimer::singleShot(0, this, SLOT(refreshFolderContextActionTriggered()));
1343 return;
1347 QMainWindow::keyPressEvent(e);
1351 * Event filter
1353 bool MainWindow::eventFilter(QObject *obj, QEvent *event)
1355 if(obj == m_fileSystemModel.data())
1357 if(QApplication::overrideCursor() == NULL)
1359 QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
1360 QTimer::singleShot(250, this, SLOT(restoreCursor()));
1364 return QMainWindow::eventFilter(obj, event);
1367 bool MainWindow::event(QEvent *e)
1369 switch(e->type())
1371 case MUtils::GUI::USER_EVENT_QUERYENDSESSION:
1372 qWarning("System is shutting down, main window prepares to close...");
1373 if(BANNER_VISIBLE) m_banner->close();
1374 if(m_delayedFileTimer->isActive()) m_delayedFileTimer->stop();
1375 return true;
1376 case MUtils::GUI::USER_EVENT_ENDSESSION:
1377 qWarning("System is shutting down, main window will close now...");
1378 if(isVisible())
1380 while(!close())
1382 QApplication::processEvents(QEventLoop::WaitForMoreEvents & QEventLoop::ExcludeUserInputEvents);
1385 m_fileListModel->clearFiles();
1386 return true;
1387 case QEvent::MouseButtonPress:
1388 if(ui->outputFolderEdit->isVisible())
1390 QTimer::singleShot(0, this, SLOT(outputFolderEditFinished()));
1392 default:
1393 return QMainWindow::event(e);
1397 bool MainWindow::winEvent(MSG *message, long *result)
1399 if(MUtils::GUI::sysmenu_check_msg(message, IDM_ABOUTBOX))
1401 QTimer::singleShot(0, ui->buttonAbout, SLOT(click()));
1402 *result = 0;
1403 return true;
1405 return false;
1408 ////////////////////////////////////////////////////////////
1409 // Slots
1410 ////////////////////////////////////////////////////////////
1412 // =========================================================
1413 // Show window slots
1414 // =========================================================
1417 * Window shown
1419 void MainWindow::windowShown(void)
1421 const MUtils::OS::ArgumentMap &arguments = MUtils::OS::arguments(); //QApplication::arguments();
1423 //Force resize event
1424 resizeEvent(NULL);
1426 //First run?
1427 const bool firstRun = arguments.contains("first-run");
1429 //Check license
1430 if((m_settings->licenseAccepted() <= 0) || firstRun)
1432 int iAccepted = m_settings->licenseAccepted();
1434 if((iAccepted == 0) || firstRun)
1436 AboutDialog *about = new AboutDialog(m_settings, this, true);
1437 iAccepted = about->exec();
1438 if(iAccepted <= 0) iAccepted = -2;
1439 MUTILS_DELETE(about);
1442 if(iAccepted <= 0)
1444 m_settings->licenseAccepted(++iAccepted);
1445 m_settings->syncNow();
1446 QApplication::processEvents();
1447 MUtils::Sound::play_sound("whammy", false);
1448 QMessageBox::critical(this, tr("License Declined"), tr("You have declined the license. Consequently the application will exit now!"), tr("Goodbye!"));
1449 QFileInfo uninstallerInfo = QFileInfo(QString("%1/Uninstall.exe").arg(QApplication::applicationDirPath()));
1450 if(uninstallerInfo.exists())
1452 QString uninstallerDir = uninstallerInfo.canonicalPath();
1453 QString uninstallerPath = uninstallerInfo.canonicalFilePath();
1454 for(int i = 0; i < 3; i++)
1456 if(MUtils::OS::shell_open(this, QDir::toNativeSeparators(uninstallerPath), "/Force", QDir::toNativeSeparators(uninstallerDir))) break;
1459 QApplication::quit();
1460 return;
1463 MUtils::Sound::play_sound("woohoo", false);
1464 m_settings->licenseAccepted(1);
1465 m_settings->syncNow();
1466 if(lamexp_version_demo()) showAnnounceBox();
1469 //Check for expiration
1470 if(lamexp_version_demo())
1472 if(MUtils::OS::current_date() >= lamexp_version_expires())
1474 qWarning("Binary has expired !!!");
1475 MUtils::Sound::play_sound("whammy", false);
1476 if(QMessageBox::warning(this, tr("LameXP - Expired"), QString("%1<br>%2").arg(NOBR(tr("This demo (pre-release) version of LameXP has expired at %1.").arg(lamexp_version_expires().toString(Qt::ISODate))), NOBR(tr("LameXP is free software and release versions won't expire."))), tr("Check for Updates"), tr("Exit Program")) == 0)
1478 checkForUpdates();
1480 QApplication::quit();
1481 return;
1485 //Slow startup indicator
1486 if(m_settings->slowStartup() && m_settings->antivirNotificationsEnabled())
1488 QString message;
1489 message += NOBR(tr("It seems that a bogus anti-virus software is slowing down the startup of LameXP.")).append("<br>");
1490 message += NOBR(tr("Please refer to the %1 document for details and solutions!")).arg(LINK_EX(QString("%1/Manual.html#performance-issues").arg(g_documents_base_url), tr("Manual"))).append("<br>");
1491 if(QMessageBox::warning(this, tr("Slow Startup"), message, tr("Discard"), tr("Don't Show Again")) == 1)
1493 m_settings->antivirNotificationsEnabled(false);
1494 ui->actionDisableSlowStartupNotifications->setChecked(!m_settings->antivirNotificationsEnabled());
1498 //Update reminder
1499 if(MUtils::OS::current_date() >= MUtils::Version::app_build_date().addYears(1))
1501 qWarning("Binary is more than a year old, time to update!");
1502 SHOW_CORNER_WIDGET(true);
1503 int ret = QMessageBox::warning(this, tr("Urgent Update"), NOBR(tr("Your version of LameXP is more than a year old. Time for an update!")), tr("Check for Updates"), tr("Exit Program"), tr("Ignore"));
1504 switch(ret)
1506 case 0:
1507 if(checkForUpdates())
1509 QApplication::quit();
1510 return;
1512 break;
1513 case 1:
1514 QApplication::quit();
1515 return;
1516 default:
1517 QEventLoop loop; QTimer::singleShot(7000, &loop, SLOT(quit()));
1518 MUtils::Sound::play_sound("waiting", true);
1519 showBanner(tr("Skipping update check this time, please be patient..."), &loop);
1520 break;
1523 else
1525 QDate lastUpdateCheck = QDate::fromString(m_settings->autoUpdateLastCheck(), Qt::ISODate);
1526 if((!firstRun) && ((!lastUpdateCheck.isValid()) || (MUtils::OS::current_date() >= lastUpdateCheck.addDays(14))))
1528 SHOW_CORNER_WIDGET(true);
1529 if(m_settings->autoUpdateEnabled())
1531 if(QMessageBox::information(this, tr("Update Reminder"), NOBR(lastUpdateCheck.isValid() ? tr("Your last update check was more than 14 days ago. Check for updates now?") : tr("Your did not check for LameXP updates yet. Check for updates now?")), tr("Check for Updates"), tr("Postpone")) == 0)
1533 if(checkForUpdates())
1535 QApplication::quit();
1536 return;
1543 //Check for AAC support
1544 const int aacEncoder = EncoderRegistry::getAacEncoder();
1545 if(aacEncoder == SettingsModel::AAC_ENCODER_NERO)
1547 if(m_settings->neroAacNotificationsEnabled())
1549 if(lamexp_tools_version("neroAacEnc.exe") < lamexp_toolver_neroaac())
1551 QString messageText;
1552 messageText += NOBR(tr("LameXP detected that your version of the Nero AAC encoder is outdated!")).append("<br>");
1553 messageText += NOBR(tr("The current version available is %1 (or later), but you still have version %2 installed.").arg(lamexp_version2string("?.?.?.?", lamexp_toolver_neroaac(), tr("n/a")), lamexp_version2string("?.?.?.?", lamexp_tools_version("neroAacEnc.exe"), tr("n/a")))).append("<br><br>");
1554 messageText += NOBR(tr("You can download the latest version of the Nero AAC encoder from the Nero website at:")).append("<br>");
1555 messageText += "<nobr><tt>" + LINK(AboutDialog::neroAacUrl) + "</tt></nobr><br><br>";
1556 messageText += NOBR(tr("(Hint: Please ignore the name of the downloaded ZIP file and check the included 'changelog.txt' instead!)")).append("<br>");
1557 QMessageBox::information(this, tr("AAC Encoder Outdated"), messageText);
1561 else
1563 if(m_settings->neroAacNotificationsEnabled() && (aacEncoder <= SettingsModel::AAC_ENCODER_NONE))
1565 QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
1566 if(appPath.isEmpty()) appPath = QCoreApplication::applicationDirPath();
1567 QString messageText;
1568 messageText += NOBR(tr("The Nero AAC encoder could not be found. AAC encoding support will be disabled.")).append("<br>");
1569 messageText += NOBR(tr("Please put 'neroAacEnc.exe', 'neroAacDec.exe' and 'neroAacTag.exe' into the LameXP directory!")).append("<br><br>");
1570 messageText += NOBR(tr("Your LameXP directory is located here:")).append("<br>");
1571 messageText += QString("<nobr><tt>%1</tt></nobr><br><br>").arg(FSLINK(QDir::toNativeSeparators(appPath)));
1572 messageText += NOBR(tr("You can download the Nero AAC encoder for free from the official Nero website at:")).append("<br>");
1573 messageText += "<nobr><tt>" + LINK(AboutDialog::neroAacUrl) + "</tt></nobr><br>";
1574 if(QMessageBox::information(this, tr("AAC Support Disabled"), messageText, tr("Discard"), tr("Don't Show Again")) == 1)
1576 m_settings->neroAacNotificationsEnabled(false);
1577 ui->actionDisableNeroAacNotifications->setChecked(!m_settings->neroAacNotificationsEnabled());
1582 //Add files from the command-line
1583 QStringList addedFiles;
1584 foreach(const QString &value, arguments.values("add"))
1586 if(!value.isEmpty())
1588 QFileInfo currentFile(value);
1589 qDebug("Adding file from CLI: %s", MUTILS_UTF8(currentFile.absoluteFilePath()));
1590 addedFiles.append(currentFile.absoluteFilePath());
1593 if(!addedFiles.isEmpty())
1595 addFilesDelayed(addedFiles);
1598 //Add folders from the command-line
1599 foreach(const QString &value, arguments.values("add-folder"))
1601 if(!value.isEmpty())
1603 const QFileInfo currentFile(value);
1604 qDebug("Adding folder from CLI: %s", MUTILS_UTF8(currentFile.absoluteFilePath()));
1605 addFolder(currentFile.absoluteFilePath(), false, true);
1608 foreach(const QString &value, arguments.values("add-recursive"))
1610 if(!value.isEmpty())
1612 const QFileInfo currentFile(value);
1613 qDebug("Adding folder recursively from CLI: %s", MUTILS_UTF8(currentFile.absoluteFilePath()));
1614 addFolder(currentFile.absoluteFilePath(), true, true);
1618 //Enable shell integration
1619 if(m_settings->shellIntegrationEnabled())
1621 ShellIntegration::install();
1624 //Make DropBox visible
1625 if(m_settings->dropBoxWidgetEnabled())
1627 m_dropBox->setVisible(true);
1632 * Show announce box
1634 void MainWindow::showAnnounceBox(void)
1636 const unsigned int timeout = 8U;
1638 const QString announceText = QString("%1<br><br>%2<br><nobr><tt>%3</tt></nobr><br>").arg
1640 NOBR("We are still looking for LameXP translators!"),
1641 NOBR("If you are willing to translate LameXP to your language or to complete an existing translation, please refer to:"),
1642 LINK("http://lamexp.sourceforge.net/doc/Translate.html")
1645 QMessageBox *announceBox = new QMessageBox(QMessageBox::Warning, "We want you!", announceText, QMessageBox::NoButton, this);
1646 announceBox->setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
1647 announceBox->setIconPixmap(QIcon(":/images/Announcement.png").pixmap(64,79));
1649 QTimer *timers[timeout+1];
1650 QPushButton *buttons[timeout+1];
1652 for(unsigned int i = 0; i <= timeout; i++)
1654 QString text = (i > 0) ? QString("%1 (%2)").arg(tr("Discard"), QString::number(i)) : tr("Discard");
1655 buttons[i] = announceBox->addButton(text, (i > 0) ? QMessageBox::NoRole : QMessageBox::AcceptRole);
1658 for(unsigned int i = 0; i <= timeout; i++)
1660 buttons[i]->setEnabled(i == 0);
1661 buttons[i]->setVisible(i == timeout);
1664 for(unsigned int i = 0; i < timeout; i++)
1666 timers[i] = new QTimer(this);
1667 timers[i]->setSingleShot(true);
1668 timers[i]->setInterval(1000);
1669 connect(timers[i], SIGNAL(timeout()), buttons[i+1], SLOT(hide()));
1670 connect(timers[i], SIGNAL(timeout()), buttons[i], SLOT(show()));
1671 if(i > 0)
1673 connect(timers[i], SIGNAL(timeout()), timers[i-1], SLOT(start()));
1677 timers[timeout-1]->start();
1678 announceBox->exec();
1680 for(unsigned int i = 0; i < timeout; i++)
1682 timers[i]->stop();
1683 MUTILS_DELETE(timers[i]);
1686 MUTILS_DELETE(announceBox);
1689 // =========================================================
1690 // Main button solots
1691 // =========================================================
1694 * Encode button
1696 void MainWindow::encodeButtonClicked(void)
1698 static const unsigned __int64 oneGigabyte = 1073741824ui64;
1699 static const unsigned __int64 minimumFreeDiskspaceMultiplier = 2ui64;
1700 static const char *writeTestBuffer = "LAMEXP_WRITE_TEST";
1702 ABORT_IF_BUSY;
1704 if(m_fileListModel->rowCount() < 1)
1706 QMessageBox::warning(this, tr("LameXP"), NOBR(tr("You must add at least one file to the list before proceeding!")));
1707 ui->tabWidget->setCurrentIndex(0);
1708 return;
1711 QString tempFolder = m_settings->customTempPathEnabled() ? m_settings->customTempPath() : MUtils::temp_folder();
1712 if(!QFileInfo(tempFolder).exists() || !QFileInfo(tempFolder).isDir())
1714 if(QMessageBox::warning(this, tr("Not Found"), QString("%1<br><tt>%2</tt>").arg(NOBR(tr("Your currently selected TEMP folder does not exist anymore:")), NOBR(QDir::toNativeSeparators(tempFolder))), tr("Restore Default"), tr("Cancel")) == 0)
1716 SET_CHECKBOX_STATE(ui->checkBoxUseSystemTempFolder, (!m_settings->customTempPathEnabledDefault()));
1718 return;
1721 quint64 currentFreeDiskspace = 0;
1722 if(MUtils::OS::free_diskspace(tempFolder, currentFreeDiskspace))
1724 if(currentFreeDiskspace < (oneGigabyte * minimumFreeDiskspaceMultiplier))
1726 QStringList tempFolderParts = tempFolder.split("/", QString::SkipEmptyParts, Qt::CaseInsensitive);
1727 tempFolderParts.takeLast();
1728 PLAY_SOUND_OPTIONAL("whammy", false);
1729 QString lowDiskspaceMsg = QString("%1<br>%2<br><br>%3<br>%4<br>").arg
1731 NOBR(tr("There are less than %1 GB of free diskspace available on your system's TEMP folder.").arg(QString::number(minimumFreeDiskspaceMultiplier))),
1732 NOBR(tr("It is highly recommend to free up more diskspace before proceeding with the encode!")),
1733 NOBR(tr("Your TEMP folder is located at:")),
1734 QString("<nobr><tt>%1</tt></nobr>").arg(FSLINK(tempFolderParts.join("\\")))
1736 switch(QMessageBox::warning(this, tr("Low Diskspace Warning"), lowDiskspaceMsg, tr("Abort Encoding Process"), tr("Clean Disk Now"), tr("Ignore")))
1738 case 1:
1739 QProcess::startDetached(QString("%1/cleanmgr.exe").arg(MUtils::OS::known_folder(MUtils::OS::FOLDER_SYSTEMFOLDER)), QStringList() << "/D" << tempFolderParts.first());
1740 case 0:
1741 return;
1742 break;
1743 default:
1744 QMessageBox::warning(this, tr("Low Diskspace"), NOBR(tr("You are proceeding with low diskspace. Problems might occur!")));
1745 break;
1750 switch(m_settings->compressionEncoder())
1752 case SettingsModel::MP3Encoder:
1753 case SettingsModel::VorbisEncoder:
1754 case SettingsModel::AACEncoder:
1755 case SettingsModel::AC3Encoder:
1756 case SettingsModel::FLACEncoder:
1757 case SettingsModel::OpusEncoder:
1758 case SettingsModel::DCAEncoder:
1759 case SettingsModel::MACEncoder:
1760 case SettingsModel::PCMEncoder:
1761 break;
1762 default:
1763 QMessageBox::warning(this, tr("LameXP"), tr("Sorry, an unsupported encoder has been chosen!"));
1764 ui->tabWidget->setCurrentIndex(3);
1765 return;
1768 if(!m_settings->outputToSourceDir())
1770 QFile writeTest(QString("%1/~%2.txt").arg(m_settings->outputDir(), MUtils::next_rand_str()));
1771 if(!(writeTest.open(QIODevice::ReadWrite) && (writeTest.write(writeTestBuffer) == strlen(writeTestBuffer))))
1773 QMessageBox::warning(this, tr("LameXP"), QString("%1<br><nobr>%2</nobr><br><br>%3").arg(tr("Cannot write to the selected output directory."), m_settings->outputDir(), tr("Please choose a different directory!")));
1774 ui->tabWidget->setCurrentIndex(1);
1775 return;
1777 else
1779 writeTest.close();
1780 writeTest.remove();
1784 m_accepted = true;
1785 close();
1789 * About button
1791 void MainWindow::aboutButtonClicked(void)
1793 ABORT_IF_BUSY;
1794 WidgetHideHelper hiderHelper(m_dropBox.data());
1795 QScopedPointer<AboutDialog> aboutBox(new AboutDialog(m_settings, this));
1796 aboutBox->exec();
1800 * Close button
1802 void MainWindow::closeButtonClicked(void)
1804 ABORT_IF_BUSY;
1805 close();
1808 // =========================================================
1809 // Tab widget slots
1810 // =========================================================
1813 * Tab page changed
1815 void MainWindow::tabPageChanged(int idx, const bool silent)
1817 resizeEvent(NULL);
1819 //Update "view" menu
1820 QList<QAction*> actions = m_tabActionGroup->actions();
1821 for(int i = 0; i < actions.count(); i++)
1823 bool ok = false;
1824 int actionIndex = actions.at(i)->data().toInt(&ok);
1825 if(ok && actionIndex == idx)
1827 actions.at(i)->setChecked(true);
1831 //Play tick sound
1832 if(!silent)
1834 PLAY_SOUND_OPTIONAL("tick", true);
1837 int initialWidth = this->width();
1838 int maximumWidth = QApplication::desktop()->availableGeometry().width();
1840 //Make sure all tab headers are fully visible
1841 if(this->isVisible())
1843 int delta = ui->tabWidget->sizeHint().width() - ui->tabWidget->width();
1844 if(delta > 0)
1846 this->resize(qMin(this->width() + delta, maximumWidth), this->height());
1850 //Tab specific operations
1851 if(idx == ui->tabWidget->indexOf(ui->tabOptions) && ui->scrollArea->widget() && this->isVisible())
1853 ui->scrollArea->widget()->updateGeometry();
1854 ui->scrollArea->viewport()->updateGeometry();
1855 qApp->processEvents();
1856 int delta = ui->scrollArea->widget()->width() - ui->scrollArea->viewport()->width();
1857 if(delta > 0)
1859 this->resize(qMin(this->width() + delta, maximumWidth), this->height());
1862 else if(idx == ui->tabWidget->indexOf(ui->tabSourceFiles))
1864 m_dropNoteLabel->setGeometry(0, 0, ui->sourceFileView->width(), ui->sourceFileView->height());
1866 else if(idx == ui->tabWidget->indexOf(ui->tabOutputDir))
1868 if(!m_fileSystemModel)
1870 QTimer::singleShot(125, this, SLOT(initOutputFolderModel()));
1872 else
1874 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED();
1878 //Center window around previous position
1879 if(initialWidth < this->width())
1881 QPoint prevPos = this->pos();
1882 int delta = (this->width() - initialWidth) >> 2;
1883 move(prevPos.x() - delta, prevPos.y());
1888 * Tab action triggered
1890 void MainWindow::tabActionActivated(QAction *action)
1892 if(action && action->data().isValid())
1894 bool ok = false;
1895 int index = action->data().toInt(&ok);
1896 if(ok)
1898 ui->tabWidget->setCurrentIndex(index);
1903 // =========================================================
1904 // Menubar slots
1905 // =========================================================
1908 * Handle corner widget Event
1910 void MainWindow::cornerWidgetEventOccurred(QWidget *sender, QEvent *event)
1912 if(event->type() == QEvent::MouseButtonPress)
1914 QTimer::singleShot(0, this, SLOT(checkUpdatesActionActivated()));
1918 // =========================================================
1919 // View menu slots
1920 // =========================================================
1923 * Style action triggered
1925 void MainWindow::styleActionActivated(QAction *action)
1927 //Change style setting
1928 if(action && action->data().isValid())
1930 bool ok = false;
1931 int actionIndex = action->data().toInt(&ok);
1932 if(ok)
1934 m_settings->interfaceStyle(actionIndex);
1938 //Set up the new style
1939 switch(m_settings->interfaceStyle())
1941 case 1:
1942 if(ui->actionStyleCleanlooks->isEnabled())
1944 ui->actionStyleCleanlooks->setChecked(true);
1945 QApplication::setStyle(new QCleanlooksStyle());
1946 break;
1948 case 2:
1949 if(ui->actionStyleWindowsVista->isEnabled())
1951 ui->actionStyleWindowsVista->setChecked(true);
1952 QApplication::setStyle(new QWindowsVistaStyle());
1953 break;
1955 case 3:
1956 if(ui->actionStyleWindowsXP->isEnabled())
1958 ui->actionStyleWindowsXP->setChecked(true);
1959 QApplication::setStyle(new QWindowsXPStyle());
1960 break;
1962 case 4:
1963 if(ui->actionStyleWindowsClassic->isEnabled())
1965 ui->actionStyleWindowsClassic->setChecked(true);
1966 QApplication::setStyle(new QWindowsStyle());
1967 break;
1969 default:
1970 ui->actionStylePlastique->setChecked(true);
1971 QApplication::setStyle(new QPlastiqueStyle());
1972 break;
1975 //Force re-translate after style change
1976 if(QEvent *e = new QEvent(QEvent::LanguageChange))
1978 changeEvent(e);
1979 MUTILS_DELETE(e);
1982 //Make transparent
1983 const type_info &styleType = typeid(*qApp->style());
1984 const bool bTransparent = ((typeid(QWindowsVistaStyle) == styleType) || (typeid(QWindowsXPStyle) == styleType));
1985 MAKE_TRANSPARENT(ui->scrollArea, bTransparent);
1987 //Also force a re-size event
1988 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
1989 resizeEvent(NULL);
1993 * Language action triggered
1995 void MainWindow::languageActionActivated(QAction *action)
1997 if(action->data().type() == QVariant::String)
1999 QString langId = action->data().toString();
2001 if(MUtils::Translation::install_translator(langId))
2003 action->setChecked(true);
2004 ui->actionLoadTranslationFromFile->setChecked(false);
2005 m_settings->currentLanguage(langId);
2006 m_settings->currentLanguageFile(QString());
2012 * Load language from file action triggered
2014 void MainWindow::languageFromFileActionActivated(bool checked)
2016 QFileDialog dialog(this, tr("Load Translation"));
2017 dialog.setFileMode(QFileDialog::ExistingFile);
2018 dialog.setNameFilter(QString("%1 (*.qm)").arg(tr("Translation Files")));
2020 if(dialog.exec())
2022 QStringList selectedFiles = dialog.selectedFiles();
2023 const QString qmFile = QFileInfo(selectedFiles.first()).canonicalFilePath();
2024 if(MUtils::Translation::install_translator_from_file(qmFile))
2026 QList<QAction*> actions = m_languageActionGroup->actions();
2027 while(!actions.isEmpty())
2029 actions.takeFirst()->setChecked(false);
2031 ui->actionLoadTranslationFromFile->setChecked(true);
2032 m_settings->currentLanguageFile(qmFile);
2034 else
2036 languageActionActivated(m_languageActionGroup->actions().first());
2041 // =========================================================
2042 // Tools menu slots
2043 // =========================================================
2046 * Disable update reminder action
2048 void MainWindow::disableUpdateReminderActionTriggered(bool checked)
2050 if(checked)
2052 if(0 == QMessageBox::question(this, tr("Disable Update Reminder"), NOBR(tr("Do you really want to disable the update reminder?")), tr("Yes"), tr("No"), QString(), 1))
2054 QMessageBox::information(this, tr("Update Reminder"), QString("%1<br>%2").arg(NOBR(tr("The update reminder has been disabled.")), NOBR(tr("Please remember to check for updates at regular intervals!"))));
2055 m_settings->autoUpdateEnabled(false);
2057 else
2059 m_settings->autoUpdateEnabled(true);
2062 else
2064 QMessageBox::information(this, tr("Update Reminder"), NOBR(tr("The update reminder has been re-enabled.")));
2065 m_settings->autoUpdateEnabled(true);
2068 ui->actionDisableUpdateReminder->setChecked(!m_settings->autoUpdateEnabled());
2072 * Disable sound effects action
2074 void MainWindow::disableSoundsActionTriggered(bool checked)
2076 if(checked)
2078 if(0 == QMessageBox::question(this, tr("Disable Sound Effects"), NOBR(tr("Do you really want to disable all sound effects?")), tr("Yes"), tr("No"), QString(), 1))
2080 QMessageBox::information(this, tr("Sound Effects"), NOBR(tr("All sound effects have been disabled.")));
2081 m_settings->soundsEnabled(false);
2083 else
2085 m_settings->soundsEnabled(true);
2088 else
2090 QMessageBox::information(this, tr("Sound Effects"), NOBR(tr("The sound effects have been re-enabled.")));
2091 m_settings->soundsEnabled(true);
2094 ui->actionDisableSounds->setChecked(!m_settings->soundsEnabled());
2098 * Disable Nero AAC encoder action
2100 void MainWindow::disableNeroAacNotificationsActionTriggered(bool checked)
2102 if(checked)
2104 if(0 == QMessageBox::question(this, tr("Nero AAC Notifications"), NOBR(tr("Do you really want to disable all Nero AAC Encoder notifications?")), tr("Yes"), tr("No"), QString(), 1))
2106 QMessageBox::information(this, tr("Nero AAC Notifications"), NOBR(tr("All Nero AAC Encoder notifications have been disabled.")));
2107 m_settings->neroAacNotificationsEnabled(false);
2109 else
2111 m_settings->neroAacNotificationsEnabled(true);
2114 else
2116 QMessageBox::information(this, tr("Nero AAC Notifications"), NOBR(tr("The Nero AAC Encoder notifications have been re-enabled.")));
2117 m_settings->neroAacNotificationsEnabled(true);
2120 ui->actionDisableNeroAacNotifications->setChecked(!m_settings->neroAacNotificationsEnabled());
2124 * Disable slow startup action
2126 void MainWindow::disableSlowStartupNotificationsActionTriggered(bool checked)
2128 if(checked)
2130 if(0 == QMessageBox::question(this, tr("Slow Startup Notifications"), NOBR(tr("Do you really want to disable the slow startup notifications?")), tr("Yes"), tr("No"), QString(), 1))
2132 QMessageBox::information(this, tr("Slow Startup Notifications"), NOBR(tr("The slow startup notifications have been disabled.")));
2133 m_settings->antivirNotificationsEnabled(false);
2135 else
2137 m_settings->antivirNotificationsEnabled(true);
2140 else
2142 QMessageBox::information(this, tr("Slow Startup Notifications"), NOBR(tr("The slow startup notifications have been re-enabled.")));
2143 m_settings->antivirNotificationsEnabled(true);
2146 ui->actionDisableSlowStartupNotifications->setChecked(!m_settings->antivirNotificationsEnabled());
2150 * Import a Cue Sheet file
2152 void MainWindow::importCueSheetActionTriggered(bool checked)
2154 ABORT_IF_BUSY;
2155 WidgetHideHelper hiderHelper(m_dropBox.data());
2157 while(true)
2159 int result = 0;
2160 QString selectedCueFile;
2162 if(MUtils::GUI::themes_enabled())
2164 selectedCueFile = QFileDialog::getOpenFileName(this, tr("Open Cue Sheet"), m_settings->mostRecentInputPath(), QString("%1 (*.cue)").arg(tr("Cue Sheet File")));
2166 else
2168 QFileDialog dialog(this, tr("Open Cue Sheet"));
2169 dialog.setFileMode(QFileDialog::ExistingFile);
2170 dialog.setNameFilter(QString("%1 (*.cue)").arg(tr("Cue Sheet File")));
2171 dialog.setDirectory(m_settings->mostRecentInputPath());
2172 if(dialog.exec())
2174 selectedCueFile = dialog.selectedFiles().first();
2178 if(!selectedCueFile.isEmpty())
2180 m_settings->mostRecentInputPath(QFileInfo(selectedCueFile).canonicalPath());
2181 FileListBlockHelper fileListBlocker(m_fileListModel);
2182 QScopedPointer<CueImportDialog> cueImporter(new CueImportDialog(this, m_fileListModel, selectedCueFile, m_settings));
2183 result = cueImporter->exec();
2186 if(result != (-1))
2188 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
2189 ui->sourceFileView->update();
2190 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
2191 ui->sourceFileView->scrollToBottom();
2192 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
2193 break;
2199 * Show the "drop box" widget
2201 void MainWindow::showDropBoxWidgetActionTriggered(bool checked)
2203 m_settings->dropBoxWidgetEnabled(true);
2205 if(!m_dropBox->isVisible())
2207 m_dropBox->show();
2208 QTimer::singleShot(2500, m_dropBox.data(), SLOT(showToolTip()));
2211 MUtils::GUI::blink_window(m_dropBox.data());
2215 * Check for beta (pre-release) updates
2217 void MainWindow::checkForBetaUpdatesActionTriggered(bool checked)
2219 bool checkUpdatesNow = false;
2221 if(checked)
2223 if(0 == QMessageBox::question(this, tr("Beta Updates"), NOBR(tr("Do you really want LameXP to check for Beta (pre-release) updates?")), tr("Yes"), tr("No"), QString(), 1))
2225 if(0 == QMessageBox::information(this, tr("Beta Updates"), NOBR(tr("LameXP will check for Beta (pre-release) updates from now on.")), tr("Check Now"), tr("Discard")))
2227 checkUpdatesNow = true;
2229 m_settings->autoUpdateCheckBeta(true);
2231 else
2233 m_settings->autoUpdateCheckBeta(false);
2236 else
2238 QMessageBox::information(this, tr("Beta Updates"), NOBR(tr("LameXP will <i>not</i> check for Beta (pre-release) updates from now on.")));
2239 m_settings->autoUpdateCheckBeta(false);
2242 ui->actionCheckForBetaUpdates->setChecked(m_settings->autoUpdateCheckBeta());
2244 if(checkUpdatesNow)
2246 if(checkForUpdates())
2248 QApplication::quit();
2254 * Hibernate computer action
2256 void MainWindow::hibernateComputerActionTriggered(bool checked)
2258 if(checked)
2260 if(0 == QMessageBox::question(this, tr("Hibernate Computer"), NOBR(tr("Do you really want the computer to be hibernated on shutdown?")), tr("Yes"), tr("No"), QString(), 1))
2262 QMessageBox::information(this, tr("Hibernate Computer"), NOBR(tr("LameXP will hibernate the computer on shutdown from now on.")));
2263 m_settings->hibernateComputer(true);
2265 else
2267 m_settings->hibernateComputer(false);
2270 else
2272 QMessageBox::information(this, tr("Hibernate Computer"), NOBR(tr("LameXP will <i>not</i> hibernate the computer on shutdown from now on.")));
2273 m_settings->hibernateComputer(false);
2276 ui->actionHibernateComputer->setChecked(m_settings->hibernateComputer());
2280 * Disable shell integration action
2282 void MainWindow::disableShellIntegrationActionTriggered(bool checked)
2284 if(checked)
2286 if(0 == QMessageBox::question(this, tr("Shell Integration"), NOBR(tr("Do you really want to disable the LameXP shell integration?")), tr("Yes"), tr("No"), QString(), 1))
2288 ShellIntegration::remove();
2289 QMessageBox::information(this, tr("Shell Integration"), NOBR(tr("The LameXP shell integration has been disabled.")));
2290 m_settings->shellIntegrationEnabled(false);
2292 else
2294 m_settings->shellIntegrationEnabled(true);
2297 else
2299 ShellIntegration::install();
2300 QMessageBox::information(this, tr("Shell Integration"), NOBR(tr("The LameXP shell integration has been re-enabled.")));
2301 m_settings->shellIntegrationEnabled(true);
2304 ui->actionDisableShellIntegration->setChecked(!m_settings->shellIntegrationEnabled());
2306 if(lamexp_version_portable() && ui->actionDisableShellIntegration->isChecked())
2308 ui->actionDisableShellIntegration->setEnabled(false);
2312 // =========================================================
2313 // Help menu slots
2314 // =========================================================
2317 * Visit homepage action
2319 void MainWindow::visitHomepageActionActivated(void)
2321 if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
2323 if(action->data().isValid() && (action->data().type() == QVariant::String))
2325 QDesktopServices::openUrl(QUrl(action->data().toString()));
2331 * Show document
2333 void MainWindow::documentActionActivated(void)
2335 if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
2337 openDocumentLink(action);
2342 * Check for updates action
2344 void MainWindow::checkUpdatesActionActivated(void)
2346 ABORT_IF_BUSY;
2347 WidgetHideHelper hiderHelper(m_dropBox.data());
2349 if(checkForUpdates())
2351 QApplication::quit();
2355 // =========================================================
2356 // Source file slots
2357 // =========================================================
2360 * Add file(s) button
2362 void MainWindow::addFilesButtonClicked(void)
2364 ABORT_IF_BUSY;
2365 WidgetHideHelper hiderHelper(m_dropBox.data());
2367 if(MUtils::GUI::themes_enabled() && (!MUTILS_DEBUG))
2369 QStringList fileTypeFilters = DecoderRegistry::getSupportedTypes();
2370 QStringList selectedFiles = QFileDialog::getOpenFileNames(this, tr("Add file(s)"), m_settings->mostRecentInputPath(), fileTypeFilters.join(";;"));
2371 if(!selectedFiles.isEmpty())
2373 m_settings->mostRecentInputPath(QFileInfo(selectedFiles.first()).canonicalPath());
2374 addFiles(selectedFiles);
2377 else
2379 QFileDialog dialog(this, tr("Add file(s)"));
2380 QStringList fileTypeFilters = DecoderRegistry::getSupportedTypes();
2381 dialog.setFileMode(QFileDialog::ExistingFiles);
2382 dialog.setNameFilter(fileTypeFilters.join(";;"));
2383 dialog.setDirectory(m_settings->mostRecentInputPath());
2384 if(dialog.exec())
2386 QStringList selectedFiles = dialog.selectedFiles();
2387 if(!selectedFiles.isEmpty())
2389 m_settings->mostRecentInputPath(QFileInfo(selectedFiles.first()).canonicalPath());
2390 addFiles(selectedFiles);
2397 * Open folder action
2399 void MainWindow::openFolderActionActivated(void)
2401 ABORT_IF_BUSY;
2402 QString selectedFolder;
2404 if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
2406 WidgetHideHelper hiderHelper(m_dropBox.data());
2407 if(MUtils::GUI::themes_enabled())
2409 selectedFolder = QFileDialog::getExistingDirectory(this, tr("Add Folder"), m_settings->mostRecentInputPath());
2411 else
2413 QFileDialog dialog(this, tr("Add Folder"));
2414 dialog.setFileMode(QFileDialog::DirectoryOnly);
2415 dialog.setDirectory(m_settings->mostRecentInputPath());
2416 if(dialog.exec())
2418 selectedFolder = dialog.selectedFiles().first();
2422 if(selectedFolder.isEmpty())
2424 return;
2427 QStringList filterItems = DecoderRegistry::getSupportedExts();
2428 filterItems.prepend("*.*");
2430 bool okay;
2431 QString filterStr = QInputDialog::getItem(this, tr("Filter Files"), tr("Select filename filter:"), filterItems, 0, false, &okay).trimmed();
2432 if(!okay)
2434 return;
2437 QRegExp regExp("\\*\\.([A-Za-z0-9]+)", Qt::CaseInsensitive);
2438 if(regExp.lastIndexIn(filterStr) >= 0)
2440 filterStr = regExp.cap(1).trimmed();
2442 else
2444 filterStr.clear();
2447 m_settings->mostRecentInputPath(QDir(selectedFolder).canonicalPath());
2448 addFolder(selectedFolder, action->data().toBool(), false, filterStr);
2453 * Remove file button
2455 void MainWindow::removeFileButtonClicked(void)
2457 const QItemSelectionModel *const selection = ui->sourceFileView->selectionModel();
2458 if(selection && selection->hasSelection())
2460 int firstRow = -1;
2461 const QModelIndexList selectedRows = INVERT_LIST(selection->selectedRows());
2462 if(!selectedRows.isEmpty())
2464 FileListBlockHelper fileListBlocker(m_fileListModel);
2465 firstRow = selectedRows.last().row();
2466 for(QModelIndexList::ConstIterator iter = selectedRows.constBegin(); iter != selectedRows.constEnd(); iter++)
2468 if(!m_fileListModel->removeFile(*iter))
2470 break;
2474 if(m_fileListModel->rowCount() > 0)
2476 const QModelIndex position = m_fileListModel->index(((firstRow >= 0) && (firstRow < m_fileListModel->rowCount())) ? firstRow : (m_fileListModel->rowCount() - 1), 0);
2477 ui->sourceFileView->selectRow(position.row());
2478 ui->sourceFileView->scrollTo(position, QAbstractItemView::PositionAtCenter);
2481 else
2483 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN);
2488 * Clear files button
2490 void MainWindow::clearFilesButtonClicked(void)
2492 if(m_fileListModel->rowCount() > 0)
2494 m_fileListModel->clearFiles();
2496 else
2498 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN);
2503 * Move file up button
2505 void MainWindow::fileUpButtonClicked(void)
2507 moveSelectedFiles(true);
2511 * Move file down button
2513 void MainWindow::fileDownButtonClicked(void)
2515 moveSelectedFiles(false);
2519 * Show details button
2521 void MainWindow::showDetailsButtonClicked(void)
2523 ABORT_IF_BUSY;
2525 int iResult = 0;
2526 QModelIndex index = ui->sourceFileView->currentIndex();
2528 if(index.isValid())
2530 ui->sourceFileView->selectRow(index.row());
2531 QScopedPointer<MetaInfoDialog> metaInfoDialog(new MetaInfoDialog(this));
2532 forever
2534 AudioFileModel &file = (*m_fileListModel)[index];
2535 WidgetHideHelper hiderHelper(m_dropBox.data());
2536 iResult = metaInfoDialog->exec(file, index.row() > 0, index.row() < m_fileListModel->rowCount() - 1);
2538 //Copy all info to Meta Info tab
2539 if(iResult == INT_MAX)
2541 m_metaInfoModel->assignInfoFrom(file);
2542 ui->tabWidget->setCurrentIndex(ui->tabWidget->indexOf(ui->tabMetaData));
2543 break;
2546 if(iResult > 0)
2548 index = m_fileListModel->index(index.row() + 1, index.column());
2549 ui->sourceFileView->selectRow(index.row());
2550 continue;
2552 else if(iResult < 0)
2554 index = m_fileListModel->index(index.row() - 1, index.column());
2555 ui->sourceFileView->selectRow(index.row());
2556 continue;
2559 break; /*close dilalog now*/
2562 else
2564 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN);
2567 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
2568 sourceFilesScrollbarMoved(0);
2572 * Show context menu for source files
2574 void MainWindow::sourceFilesContextMenu(const QPoint &pos)
2576 QAbstractScrollArea *scrollArea = dynamic_cast<QAbstractScrollArea*>(QObject::sender());
2577 QWidget *sender = scrollArea ? scrollArea->viewport() : dynamic_cast<QWidget*>(QObject::sender());
2579 if(sender)
2581 if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0)
2583 m_sourceFilesContextMenu->popup(sender->mapToGlobal(pos));
2589 * Scrollbar of source files moved
2591 void MainWindow::sourceFilesScrollbarMoved(int)
2593 ui->sourceFileView->resizeColumnToContents(0);
2597 * Open selected file in external player
2599 void MainWindow::previewContextActionTriggered(void)
2601 QModelIndex index = ui->sourceFileView->currentIndex();
2602 if(!index.isValid())
2604 return;
2607 if(!MUtils::OS::open_media_file(m_fileListModel->getFile(index).filePath()))
2609 qDebug("Player not found, falling back to default application...");
2610 QDesktopServices::openUrl(QString("file:///").append(m_fileListModel->getFile(index).filePath()));
2615 * Find selected file in explorer
2617 void MainWindow::findFileContextActionTriggered(void)
2619 QModelIndex index = ui->sourceFileView->currentIndex();
2620 if(index.isValid())
2622 QString systemRootPath;
2624 QDir systemRoot(MUtils::OS::known_folder(MUtils::OS::FOLDER_SYSTEMFOLDER));
2625 if(systemRoot.exists() && systemRoot.cdUp())
2627 systemRootPath = systemRoot.canonicalPath();
2630 if(!systemRootPath.isEmpty())
2632 QFileInfo explorer(QString("%1/explorer.exe").arg(systemRootPath));
2633 if(explorer.exists() && explorer.isFile())
2635 QProcess::execute(explorer.canonicalFilePath(), QStringList() << "/select," << QDir::toNativeSeparators(m_fileListModel->getFile(index).filePath()));
2636 return;
2639 else
2641 qWarning("SystemRoot directory could not be detected!");
2647 * Add all dropped files
2649 void MainWindow::handleDroppedFiles(void)
2651 ABORT_IF_BUSY;
2653 static const int MIN_COUNT = 16;
2654 const QString bannerText = tr("Loading dropped files or folders, please wait...");
2655 bool bUseBanner = false;
2657 showBanner(bannerText, bUseBanner, (m_droppedFileList->count() >= MIN_COUNT));
2659 QStringList droppedFiles;
2660 while(!m_droppedFileList->isEmpty())
2662 QFileInfo file(m_droppedFileList->takeFirst().toLocalFile());
2663 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
2665 if(!file.exists())
2667 continue;
2670 if(file.isFile())
2672 qDebug("Dropped File: %s", MUTILS_UTF8(file.canonicalFilePath()));
2673 droppedFiles << file.canonicalFilePath();
2674 continue;
2677 if(file.isDir())
2679 qDebug("Dropped Folder: %s", MUTILS_UTF8(file.canonicalFilePath()));
2680 QFileInfoList list = QDir(file.canonicalFilePath()).entryInfoList(QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks);
2681 if(list.count() > 0)
2683 showBanner(bannerText, bUseBanner, (list.count() >= MIN_COUNT));
2684 for(QFileInfoList::ConstIterator iter = list.constBegin(); iter != list.constEnd(); iter++)
2686 droppedFiles << (*iter).canonicalFilePath();
2689 else
2691 list = QDir(file.canonicalFilePath()).entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks);
2692 showBanner(bannerText, bUseBanner, (list.count() >= MIN_COUNT));
2693 for(QFileInfoList::ConstIterator iter = list.constBegin(); iter != list.constEnd(); iter++)
2695 qDebug("Descending to Folder: %s", MUTILS_UTF8((*iter).canonicalFilePath()));
2696 m_droppedFileList->prepend(QUrl::fromLocalFile((*iter).canonicalFilePath()));
2702 if(bUseBanner)
2704 m_banner->close();
2707 if(!droppedFiles.isEmpty())
2709 addFiles(droppedFiles);
2714 * Add all pending files
2716 void MainWindow::handleDelayedFiles(void)
2718 m_delayedFileTimer->stop();
2720 if(m_delayedFileList->isEmpty())
2722 return;
2725 if(BANNER_VISIBLE)
2727 m_delayedFileTimer->start(5000);
2728 return;
2731 if(ui->tabWidget->currentIndex() != 0)
2733 SignalBlockHelper signalBlockHelper(ui->tabWidget);
2734 ui->tabWidget->setCurrentIndex(0);
2735 tabPageChanged(ui->tabWidget->currentIndex(), true);
2738 QStringList selectedFiles;
2739 while(!m_delayedFileList->isEmpty())
2741 QFileInfo currentFile = QFileInfo(m_delayedFileList->takeFirst());
2742 if(!currentFile.exists() || !currentFile.isFile())
2744 continue;
2746 selectedFiles << currentFile.canonicalFilePath();
2749 addFiles(selectedFiles);
2753 * Export Meta tags to CSV file
2755 void MainWindow::exportCsvContextActionTriggered(void)
2757 ABORT_IF_BUSY;
2758 WidgetHideHelper hiderHelper(m_dropBox.data());
2760 QString selectedCsvFile;
2761 if(MUtils::GUI::themes_enabled())
2763 selectedCsvFile = QFileDialog::getSaveFileName(this, tr("Save CSV file"), m_settings->mostRecentInputPath(), QString("%1 (*.csv)").arg(tr("CSV File")));
2765 else
2767 QFileDialog dialog(this, tr("Save CSV file"));
2768 dialog.setFileMode(QFileDialog::AnyFile);
2769 dialog.setAcceptMode(QFileDialog::AcceptSave);
2770 dialog.setNameFilter(QString("%1 (*.csv)").arg(tr("CSV File")));
2771 dialog.setDirectory(m_settings->mostRecentInputPath());
2772 if(dialog.exec())
2774 selectedCsvFile = dialog.selectedFiles().first();
2778 if(!selectedCsvFile.isEmpty())
2780 m_settings->mostRecentInputPath(QFileInfo(selectedCsvFile).canonicalPath());
2781 switch(m_fileListModel->exportToCsv(selectedCsvFile))
2783 case FileListModel::CsvError_NoTags:
2784 QMessageBox::critical(this, tr("CSV Export"), NOBR(tr("Sorry, there are no meta tags that can be exported!")));
2785 break;
2786 case FileListModel::CsvError_FileOpen:
2787 QMessageBox::critical(this, tr("CSV Export"), NOBR(tr("Sorry, failed to open CSV file for writing!")));
2788 break;
2789 case FileListModel::CsvError_FileWrite:
2790 QMessageBox::critical(this, tr("CSV Export"), NOBR(tr("Sorry, failed to write to the CSV file!")));
2791 break;
2792 case FileListModel::CsvError_OK:
2793 QMessageBox::information(this, tr("CSV Export"), NOBR(tr("The CSV files was created successfully!")));
2794 break;
2795 default:
2796 qWarning("exportToCsv: Unknown return code!");
2803 * Import Meta tags from CSV file
2805 void MainWindow::importCsvContextActionTriggered(void)
2807 ABORT_IF_BUSY;
2808 WidgetHideHelper hiderHelper(m_dropBox.data());
2810 QString selectedCsvFile;
2811 if(MUtils::GUI::themes_enabled())
2813 selectedCsvFile = QFileDialog::getOpenFileName(this, tr("Open CSV file"), m_settings->mostRecentInputPath(), QString("%1 (*.csv)").arg(tr("CSV File")));
2815 else
2817 QFileDialog dialog(this, tr("Open CSV file"));
2818 dialog.setFileMode(QFileDialog::ExistingFile);
2819 dialog.setNameFilter(QString("%1 (*.csv)").arg(tr("CSV File")));
2820 dialog.setDirectory(m_settings->mostRecentInputPath());
2821 if(dialog.exec())
2823 selectedCsvFile = dialog.selectedFiles().first();
2827 if(!selectedCsvFile.isEmpty())
2829 m_settings->mostRecentInputPath(QFileInfo(selectedCsvFile).canonicalPath());
2830 switch(m_fileListModel->importFromCsv(this, selectedCsvFile))
2832 case FileListModel::CsvError_FileOpen:
2833 QMessageBox::critical(this, tr("CSV Import"), NOBR(tr("Sorry, failed to open CSV file for reading!")));
2834 break;
2835 case FileListModel::CsvError_FileRead:
2836 QMessageBox::critical(this, tr("CSV Import"), NOBR(tr("Sorry, failed to read from the CSV file!")));
2837 break;
2838 case FileListModel::CsvError_NoTags:
2839 QMessageBox::critical(this, tr("CSV Import"), NOBR(tr("Sorry, the CSV file does not contain any known fields!")));
2840 break;
2841 case FileListModel::CsvError_Incomplete:
2842 QMessageBox::warning(this, tr("CSV Import"), NOBR(tr("CSV file is incomplete. Not all files were updated!")));
2843 break;
2844 case FileListModel::CsvError_OK:
2845 QMessageBox::information(this, tr("CSV Import"), NOBR(tr("The CSV files was imported successfully!")));
2846 break;
2847 case FileListModel::CsvError_Aborted:
2848 /* User aborted, ignore! */
2849 break;
2850 default:
2851 qWarning("exportToCsv: Unknown return code!");
2857 * Show or hide Drag'n'Drop notice after model reset
2859 void MainWindow::sourceModelChanged(void)
2861 m_dropNoteLabel->setVisible(m_fileListModel->rowCount() <= 0);
2864 // =========================================================
2865 // Output folder slots
2866 // =========================================================
2869 * Output folder changed (mouse clicked)
2871 void MainWindow::outputFolderViewClicked(const QModelIndex &index)
2873 if(index.isValid() && (ui->outputFolderView->currentIndex() != index))
2875 ui->outputFolderView->setCurrentIndex(index);
2878 if(m_fileSystemModel && index.isValid())
2880 QString selectedDir = m_fileSystemModel->filePath(index);
2881 if(selectedDir.length() < 3) selectedDir.append(QDir::separator());
2882 ui->outputFolderLabel->setText(QDir::toNativeSeparators(selectedDir));
2883 ui->outputFolderLabel->setToolTip(ui->outputFolderLabel->text());
2884 m_settings->outputDir(selectedDir);
2886 else
2888 ui->outputFolderLabel->setText(QDir::toNativeSeparators(m_settings->outputDir()));
2889 ui->outputFolderLabel->setToolTip(ui->outputFolderLabel->text());
2894 * Output folder changed (mouse moved)
2896 void MainWindow::outputFolderViewMoved(const QModelIndex &index)
2898 if(QApplication::mouseButtons() & Qt::LeftButton)
2900 outputFolderViewClicked(index);
2905 * Goto desktop button
2907 void MainWindow::gotoDesktopButtonClicked(void)
2909 if(!m_fileSystemModel)
2911 qWarning("File system model not initialized yet!");
2912 return;
2915 QString desktopPath = QDesktopServices::storageLocation(QDesktopServices::DesktopLocation);
2917 if(!desktopPath.isEmpty() && QDir(desktopPath).exists())
2919 ui->outputFolderView->setCurrentIndex(m_fileSystemModel->index(desktopPath));
2920 outputFolderViewClicked(ui->outputFolderView->currentIndex());
2921 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED();
2923 else
2925 ui->buttonGotoDesktop->setEnabled(false);
2930 * Goto home folder button
2932 void MainWindow::gotoHomeFolderButtonClicked(void)
2934 if(!m_fileSystemModel)
2936 qWarning("File system model not initialized yet!");
2937 return;
2940 QString homePath = QDesktopServices::storageLocation(QDesktopServices::HomeLocation);
2942 if(!homePath.isEmpty() && QDir(homePath).exists())
2944 ui->outputFolderView->setCurrentIndex(m_fileSystemModel->index(homePath));
2945 outputFolderViewClicked(ui->outputFolderView->currentIndex());
2946 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED();
2948 else
2950 ui->buttonGotoHome->setEnabled(false);
2955 * Goto music folder button
2957 void MainWindow::gotoMusicFolderButtonClicked(void)
2959 if(!m_fileSystemModel)
2961 qWarning("File system model not initialized yet!");
2962 return;
2965 QString musicPath = QDesktopServices::storageLocation(QDesktopServices::MusicLocation);
2967 if(!musicPath.isEmpty() && QDir(musicPath).exists())
2969 ui->outputFolderView->setCurrentIndex(m_fileSystemModel->index(musicPath));
2970 outputFolderViewClicked(ui->outputFolderView->currentIndex());
2971 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED();
2973 else
2975 ui->buttonGotoMusic->setEnabled(false);
2980 * Goto music favorite output folder
2982 void MainWindow::gotoFavoriteFolder(void)
2984 if(!m_fileSystemModel)
2986 qWarning("File system model not initialized yet!");
2987 return;
2990 QAction *item = dynamic_cast<QAction*>(QObject::sender());
2992 if(item)
2994 QDir path(item->data().toString());
2995 if(path.exists())
2997 ui->outputFolderView->setCurrentIndex(m_fileSystemModel->index(path.canonicalPath()));
2998 outputFolderViewClicked(ui->outputFolderView->currentIndex());
2999 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED();
3001 else
3003 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
3004 m_outputFolderFavoritesMenu->removeAction(item);
3005 item->deleteLater();
3011 * Make folder button
3013 void MainWindow::makeFolderButtonClicked(void)
3015 ABORT_IF_BUSY;
3017 if(!m_fileSystemModel)
3019 qWarning("File system model not initialized yet!");
3020 return;
3023 QDir basePath(m_fileSystemModel->fileInfo(ui->outputFolderView->currentIndex()).absoluteFilePath());
3024 QString suggestedName = tr("New Folder");
3026 if(!m_metaData->artist().isEmpty() && !m_metaData->album().isEmpty())
3028 suggestedName = QString("%1 - %2").arg(m_metaData->artist(),m_metaData->album());
3030 else if(!m_metaData->artist().isEmpty())
3032 suggestedName = m_metaData->artist();
3034 else if(!m_metaData->album().isEmpty())
3036 suggestedName =m_metaData->album();
3038 else
3040 for(int i = 0; i < m_fileListModel->rowCount(); i++)
3042 const AudioFileModel &audioFile = m_fileListModel->getFile(m_fileListModel->index(i, 0));
3043 const AudioFileModel_MetaInfo &fileMetaInfo = audioFile.metaInfo();
3045 if(!fileMetaInfo.album().isEmpty() || !fileMetaInfo.artist().isEmpty())
3047 if(!fileMetaInfo.artist().isEmpty() && !fileMetaInfo.album().isEmpty())
3049 suggestedName = QString("%1 - %2").arg(fileMetaInfo.artist(), fileMetaInfo.album());
3051 else if(!fileMetaInfo.artist().isEmpty())
3053 suggestedName = fileMetaInfo.artist();
3055 else if(!fileMetaInfo.album().isEmpty())
3057 suggestedName = fileMetaInfo.album();
3059 break;
3064 suggestedName = MUtils::clean_file_name(suggestedName);
3066 while(true)
3068 bool bApplied = false;
3069 QString folderName = QInputDialog::getText(this, tr("New Folder"), tr("Enter the name of the new folder:").leftJustified(96, ' '), QLineEdit::Normal, suggestedName, &bApplied, Qt::WindowStaysOnTopHint).simplified();
3071 if(bApplied)
3073 folderName = MUtils::clean_file_path(folderName.simplified());
3075 if(folderName.isEmpty())
3077 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
3078 continue;
3081 int i = 1;
3082 QString newFolder = folderName;
3084 while(basePath.exists(newFolder))
3086 newFolder = QString(folderName).append(QString().sprintf(" (%d)", ++i));
3089 if(basePath.mkpath(newFolder))
3091 QDir createdDir = basePath;
3092 if(createdDir.cd(newFolder))
3094 QModelIndex newIndex = m_fileSystemModel->index(createdDir.canonicalPath());
3095 ui->outputFolderView->setCurrentIndex(newIndex);
3096 outputFolderViewClicked(newIndex);
3097 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED();
3100 else
3102 QMessageBox::warning(this, tr("Failed to create folder"), QString("%1<br><nobr>%2</nobr><br><br>%3").arg(tr("The new folder could not be created:"), basePath.absoluteFilePath(newFolder), tr("Drive is read-only or insufficient access rights!")));
3105 break;
3110 * Output to source dir changed
3112 void MainWindow::saveToSourceFolderChanged(void)
3114 m_settings->outputToSourceDir(ui->saveToSourceFolderCheckBox->isChecked());
3118 * Prepend relative source file path to output file name changed
3120 void MainWindow::prependRelativePathChanged(void)
3122 m_settings->prependRelativeSourcePath(ui->prependRelativePathCheckBox->isChecked());
3126 * Show context menu for output folder
3128 void MainWindow::outputFolderContextMenu(const QPoint &pos)
3130 QAbstractScrollArea *scrollArea = dynamic_cast<QAbstractScrollArea*>(QObject::sender());
3131 QWidget *sender = scrollArea ? scrollArea->viewport() : dynamic_cast<QWidget*>(QObject::sender());
3133 if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0)
3135 m_outputFolderContextMenu->popup(sender->mapToGlobal(pos));
3140 * Show selected folder in explorer
3142 void MainWindow::showFolderContextActionTriggered(void)
3144 if(!m_fileSystemModel)
3146 qWarning("File system model not initialized yet!");
3147 return;
3150 QString path = QDir::toNativeSeparators(m_fileSystemModel->filePath(ui->outputFolderView->currentIndex()));
3151 if(!path.endsWith(QDir::separator())) path.append(QDir::separator());
3152 MUtils::OS::shell_open(this, path, true);
3156 * Refresh the directory outline
3158 void MainWindow::refreshFolderContextActionTriggered(void)
3160 //force re-initialization
3161 QTimer::singleShot(0, this, SLOT(initOutputFolderModel()));
3165 * Go one directory up
3167 void MainWindow::goUpFolderContextActionTriggered(void)
3169 QModelIndex current = ui->outputFolderView->currentIndex();
3170 if(current.isValid())
3172 QModelIndex parent = current.parent();
3173 if(parent.isValid())
3176 ui->outputFolderView->setCurrentIndex(parent);
3177 outputFolderViewClicked(parent);
3179 else
3181 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN);
3183 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED();
3188 * Add current folder to favorites
3190 void MainWindow::addFavoriteFolderActionTriggered(void)
3192 QString path = m_fileSystemModel->filePath(ui->outputFolderView->currentIndex());
3193 QStringList favorites = m_settings->favoriteOutputFolders().split("|", QString::SkipEmptyParts);
3195 if(!favorites.contains(path, Qt::CaseInsensitive))
3197 favorites.append(path);
3198 while(favorites.count() > 6) favorites.removeFirst();
3200 else
3202 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN);
3205 m_settings->favoriteOutputFolders(favorites.join("|"));
3206 refreshFavorites();
3210 * Output folder edit finished
3212 void MainWindow::outputFolderEditFinished(void)
3214 if(ui->outputFolderEdit->isHidden())
3216 return; //Not currently in edit mode!
3219 bool ok = false;
3221 QString text = QDir::fromNativeSeparators(ui->outputFolderEdit->text().trimmed());
3222 while(text.startsWith('"') || text.startsWith('/')) text = text.right(text.length() - 1).trimmed();
3223 while(text.endsWith('"') || text.endsWith('/')) text = text.left(text.length() - 1).trimmed();
3225 static const char *str = "?*<>|\"";
3226 for(size_t i = 0; str[i]; i++) text.replace(str[i], "_");
3228 if(!((text.length() >= 2) && text.at(0).isLetter() && text.at(1) == QChar(':')))
3230 text = QString("%1/%2").arg(QDir::fromNativeSeparators(ui->outputFolderLabel->text()), text);
3233 if(text.length() == 2) text += "/"; /* "X:" => "X:/" */
3235 while(text.length() > 2)
3237 QFileInfo info(text);
3238 if(info.exists() && info.isDir())
3240 QModelIndex index = m_fileSystemModel->index(QFileInfo(info.canonicalFilePath()).absoluteFilePath());
3241 if(index.isValid())
3243 ok = true;
3244 ui->outputFolderView->setCurrentIndex(index);
3245 outputFolderViewClicked(index);
3246 break;
3249 else if(info.exists() && info.isFile())
3251 QModelIndex index = m_fileSystemModel->index(QFileInfo(info.canonicalPath()).absoluteFilePath());
3252 if(index.isValid())
3254 ok = true;
3255 ui->outputFolderView->setCurrentIndex(index);
3256 outputFolderViewClicked(index);
3257 break;
3261 text = text.left(text.length() - 1).trimmed();
3264 ui->outputFolderEdit->setVisible(false);
3265 ui->outputFolderLabel->setVisible(true);
3266 ui->outputFolderView->setEnabled(true);
3268 if(!ok) MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
3269 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED();
3273 * Initialize file system model
3275 void MainWindow::initOutputFolderModel(void)
3277 if(m_outputFolderNoteBox->isHidden())
3279 m_outputFolderNoteBox->show();
3280 m_outputFolderNoteBox->repaint();
3281 m_outputFolderViewInitCounter = 4;
3283 if(m_fileSystemModel)
3285 SET_MODEL(ui->outputFolderView, NULL);
3286 ui->outputFolderView->repaint();
3289 m_fileSystemModel.reset(new QFileSystemModelEx());
3290 if(!m_fileSystemModel.isNull())
3292 m_fileSystemModel->installEventFilter(this);
3293 connect(m_fileSystemModel.data(), SIGNAL(directoryLoaded(QString)), this, SLOT(outputFolderDirectoryLoaded(QString)));
3294 connect(m_fileSystemModel.data(), SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(outputFolderRowsInserted(QModelIndex,int,int)));
3296 SET_MODEL(ui->outputFolderView, m_fileSystemModel.data());
3297 ui->outputFolderView->header()->setStretchLastSection(true);
3298 ui->outputFolderView->header()->hideSection(1);
3299 ui->outputFolderView->header()->hideSection(2);
3300 ui->outputFolderView->header()->hideSection(3);
3302 m_fileSystemModel->setRootPath("");
3303 QModelIndex index = m_fileSystemModel->index(m_settings->outputDir());
3304 if(index.isValid()) ui->outputFolderView->setCurrentIndex(index);
3305 outputFolderViewClicked(ui->outputFolderView->currentIndex());
3308 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED();
3309 QTimer::singleShot(125, this, SLOT(initOutputFolderModel_doAsync()));
3314 * Initialize file system model (do NOT call this one directly!)
3316 void MainWindow::initOutputFolderModel_doAsync(void)
3318 if(m_outputFolderViewInitCounter > 0)
3320 m_outputFolderViewInitCounter--;
3321 QTimer::singleShot(125, this, SLOT(initOutputFolderModel_doAsync()));
3323 else
3325 QTimer::singleShot(125, m_outputFolderNoteBox.data(), SLOT(hide()));
3326 ui->outputFolderView->setFocus();
3331 * Center current folder in view
3333 void MainWindow::centerOutputFolderModel(void)
3335 if(ui->outputFolderView->isVisible())
3337 centerOutputFolderModel_doAsync();
3338 QTimer::singleShot(125, this, SLOT(centerOutputFolderModel_doAsync()));
3343 * Center current folder in view (do NOT call this one directly!)
3345 void MainWindow::centerOutputFolderModel_doAsync(void)
3347 if(ui->outputFolderView->isVisible())
3349 m_outputFolderViewCentering = true;
3350 const QModelIndex index = ui->outputFolderView->currentIndex();
3351 ui->outputFolderView->scrollTo(index, QAbstractItemView::PositionAtCenter);
3352 ui->outputFolderView->setFocus();
3357 * File system model asynchronously loaded a dir
3359 void MainWindow::outputFolderDirectoryLoaded(const QString &path)
3361 if(m_outputFolderViewCentering)
3363 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED();
3368 * File system model inserted new items
3370 void MainWindow::outputFolderRowsInserted(const QModelIndex &parent, int start, int end)
3372 if(m_outputFolderViewCentering)
3374 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED();
3379 * Directory view item was expanded by user
3381 void MainWindow::outputFolderItemExpanded(const QModelIndex &item)
3383 //We need to stop centering as soon as the user has expanded an item manually!
3384 m_outputFolderViewCentering = false;
3388 * View event for output folder control occurred
3390 void MainWindow::outputFolderViewEventOccurred(QWidget *sender, QEvent *event)
3392 switch(event->type())
3394 case QEvent::Enter:
3395 case QEvent::Leave:
3396 case QEvent::KeyPress:
3397 case QEvent::KeyRelease:
3398 case QEvent::FocusIn:
3399 case QEvent::FocusOut:
3400 case QEvent::TouchEnd:
3401 outputFolderViewClicked(ui->outputFolderView->currentIndex());
3402 break;
3407 * Mouse event for output folder control occurred
3409 void MainWindow::outputFolderMouseEventOccurred(QWidget *sender, QEvent *event)
3411 QMouseEvent *mouseEvent = dynamic_cast<QMouseEvent*>(event);
3412 QPoint pos = (mouseEvent) ? mouseEvent->pos() : QPoint();
3414 if(sender == ui->outputFolderLabel)
3416 switch(event->type())
3418 case QEvent::MouseButtonPress:
3419 if(mouseEvent && (mouseEvent->button() == Qt::LeftButton))
3421 QString path = ui->outputFolderLabel->text();
3422 if(!path.endsWith(QDir::separator())) path.append(QDir::separator());
3423 MUtils::OS::shell_open(this, path, true);
3425 break;
3426 case QEvent::Enter:
3427 ui->outputFolderLabel->setForegroundRole(QPalette::Link);
3428 break;
3429 case QEvent::Leave:
3430 ui->outputFolderLabel->setForegroundRole(QPalette::WindowText);
3431 break;
3435 if((sender == ui->outputFoldersFovoritesLabel) || (sender == ui->outputFoldersEditorLabel) || (sender == ui->outputFoldersGoUpLabel))
3437 const type_info &styleType = typeid(*qApp->style());
3438 if((typeid(QPlastiqueStyle) == styleType) || (typeid(QWindowsStyle) == styleType))
3440 switch(event->type())
3442 case QEvent::Enter:
3443 dynamic_cast<QLabel*>(sender)->setFrameShadow(ui->outputFolderView->isEnabled() ? QFrame::Raised : QFrame::Plain);
3444 break;
3445 case QEvent::MouseButtonPress:
3446 dynamic_cast<QLabel*>(sender)->setFrameShadow(ui->outputFolderView->isEnabled() ? QFrame::Sunken : QFrame::Plain);
3447 break;
3448 case QEvent::MouseButtonRelease:
3449 dynamic_cast<QLabel*>(sender)->setFrameShadow(ui->outputFolderView->isEnabled() ? QFrame::Raised : QFrame::Plain);
3450 break;
3451 case QEvent::Leave:
3452 dynamic_cast<QLabel*>(sender)->setFrameShadow(ui->outputFolderView->isEnabled() ? QFrame::Plain : QFrame::Plain);
3453 break;
3456 else
3458 dynamic_cast<QLabel*>(sender)->setFrameShadow(QFrame::Plain);
3461 if((event->type() == QEvent::MouseButtonRelease) && ui->outputFolderView->isEnabled() && (mouseEvent))
3463 if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0 && mouseEvent->button() != Qt::MidButton)
3465 if(sender == ui->outputFoldersFovoritesLabel)
3467 m_outputFolderFavoritesMenu->popup(sender->mapToGlobal(pos));
3469 else if(sender == ui->outputFoldersEditorLabel)
3471 ui->outputFolderView->setEnabled(false);
3472 ui->outputFolderLabel->setVisible(false);
3473 ui->outputFolderEdit->setVisible(true);
3474 ui->outputFolderEdit->setText(ui->outputFolderLabel->text());
3475 ui->outputFolderEdit->selectAll();
3476 ui->outputFolderEdit->setFocus();
3478 else if(sender == ui->outputFoldersGoUpLabel)
3480 QTimer::singleShot(0, this, SLOT(goUpFolderContextActionTriggered()));
3482 else
3484 MUTILS_THROW("Oups, this is not supposed to happen!");
3491 // =========================================================
3492 // Metadata tab slots
3493 // =========================================================
3496 * Edit meta button clicked
3498 void MainWindow::editMetaButtonClicked(void)
3500 ABORT_IF_BUSY;
3502 const QModelIndex index = ui->metaDataView->currentIndex();
3504 if(index.isValid())
3506 m_metaInfoModel->editItem(index, this);
3508 if(index.row() == 4)
3510 m_settings->metaInfoPosition(m_metaData->position());
3516 * Reset meta button clicked
3518 void MainWindow::clearMetaButtonClicked(void)
3520 ABORT_IF_BUSY;
3521 m_metaInfoModel->clearData();
3525 * Meta tags enabled changed
3527 void MainWindow::metaTagsEnabledChanged(void)
3529 m_settings->writeMetaTags(ui->writeMetaDataCheckBox->isChecked());
3533 * Playlist enabled changed
3535 void MainWindow::playlistEnabledChanged(void)
3537 m_settings->createPlaylist(ui->generatePlaylistCheckBox->isChecked());
3540 // =========================================================
3541 // Compression tab slots
3542 // =========================================================
3545 * Update encoder
3547 void MainWindow::updateEncoder(int id)
3549 /*qWarning("\nupdateEncoder(%d)", id);*/
3551 m_settings->compressionEncoder(id);
3552 const AbstractEncoderInfo *info = EncoderRegistry::getEncoderInfo(id);
3554 //Update UI controls
3555 ui->radioButtonModeQuality ->setEnabled(info->isModeSupported(SettingsModel::VBRMode));
3556 ui->radioButtonModeAverageBitrate->setEnabled(info->isModeSupported(SettingsModel::ABRMode));
3557 ui->radioButtonConstBitrate ->setEnabled(info->isModeSupported(SettingsModel::CBRMode));
3559 //Initialize checkbox state
3560 if(ui->radioButtonModeQuality->isEnabled()) ui->radioButtonModeQuality->setChecked(true);
3561 else if(ui->radioButtonModeAverageBitrate->isEnabled()) ui->radioButtonModeAverageBitrate->setChecked(true);
3562 else if(ui->radioButtonConstBitrate->isEnabled()) ui->radioButtonConstBitrate->setChecked(true);
3563 else MUTILS_THROW("It appears that the encoder does not support *any* RC mode!");
3565 //Apply current RC mode
3566 const int currentRCMode = EncoderRegistry::loadEncoderMode(m_settings, id);
3567 switch(currentRCMode)
3569 case SettingsModel::VBRMode: if(ui->radioButtonModeQuality->isEnabled()) ui->radioButtonModeQuality->setChecked(true); break;
3570 case SettingsModel::ABRMode: if(ui->radioButtonModeAverageBitrate->isEnabled()) ui->radioButtonModeAverageBitrate->setChecked(true); break;
3571 case SettingsModel::CBRMode: if(ui->radioButtonConstBitrate->isEnabled()) ui->radioButtonConstBitrate->setChecked(true); break;
3572 default: MUTILS_THROW("updateEncoder(): Unknown rc-mode encountered!");
3575 //Display encoder description
3576 if(const char* description = info->description())
3578 ui->labelEncoderInfo->setVisible(true);
3579 ui->labelEncoderInfo->setText(tr("Current Encoder: %1").arg(QString::fromUtf8(description)));
3581 else
3583 ui->labelEncoderInfo->setVisible(false);
3586 //Update RC mode!
3587 updateRCMode(m_modeButtonGroup->checkedId());
3591 * Update rate-control mode
3593 void MainWindow::updateRCMode(int id)
3595 /*qWarning("updateRCMode(%d)", id);*/
3597 //Store new RC mode
3598 const int currentEncoder = m_encoderButtonGroup->checkedId();
3599 EncoderRegistry::saveEncoderMode(m_settings, currentEncoder, id);
3601 //Fetch encoder info
3602 const AbstractEncoderInfo *info = EncoderRegistry::getEncoderInfo(currentEncoder);
3603 const int valueCount = info->valueCount(id);
3605 //Sanity check
3606 if(!info->isModeSupported(id))
3608 qWarning("Attempting to use an unsupported RC mode (%d) with current encoder (%d)!", id, currentEncoder);
3609 ui->labelBitrate->setText("(ERROR)");
3610 return;
3613 //Update slider min/max values
3614 if(valueCount > 0)
3616 SignalBlockHelper signalBlockHelper(ui->sliderBitrate);
3617 ui->sliderBitrate->setEnabled(true);
3618 ui->sliderBitrate->setMinimum(0);
3619 ui->sliderBitrate->setMaximum(valueCount-1);
3621 else
3623 SignalBlockHelper signalBlockHelper(ui->sliderBitrate);
3624 ui->sliderBitrate->setEnabled(false);
3625 ui->sliderBitrate->setMinimum(0);
3626 ui->sliderBitrate->setMaximum(2);
3629 //Now update bitrate/quality value!
3630 if(valueCount > 0)
3632 const int currentValue = EncoderRegistry::loadEncoderValue(m_settings, currentEncoder, id);
3633 ui->sliderBitrate->setValue(qBound(0, currentValue, valueCount-1));
3634 updateBitrate(qBound(0, currentValue, valueCount-1));
3636 else
3638 ui->sliderBitrate->setValue(1);
3639 updateBitrate(0);
3644 * Update bitrate
3646 void MainWindow::updateBitrate(int value)
3648 /*qWarning("updateBitrate(%d)", value);*/
3650 //Load current encoder and RC mode
3651 const int currentEncoder = m_encoderButtonGroup->checkedId();
3652 const int currentRCMode = m_modeButtonGroup->checkedId();
3654 //Fetch encoder info
3655 const AbstractEncoderInfo *info = EncoderRegistry::getEncoderInfo(currentEncoder);
3656 const int valueCount = info->valueCount(currentRCMode);
3658 //Sanity check
3659 if(!info->isModeSupported(currentRCMode))
3661 qWarning("Attempting to use an unsupported RC mode (%d) with current encoder (%d)!", currentRCMode, currentEncoder);
3662 ui->labelBitrate->setText("(ERROR)");
3663 return;
3666 //Store new bitrate value
3667 if(valueCount > 0)
3669 EncoderRegistry::saveEncoderValue(m_settings, currentEncoder, currentRCMode, qBound(0, value, valueCount-1));
3672 //Update bitrate value
3673 const int displayValue = (valueCount > 0) ? info->valueAt(currentRCMode, qBound(0, value, valueCount-1)) : INT_MAX;
3674 switch(info->valueType(currentRCMode))
3676 case AbstractEncoderInfo::TYPE_BITRATE:
3677 ui->labelBitrate->setText(QString("%1 kbps").arg(QString::number(displayValue)));
3678 break;
3679 case AbstractEncoderInfo::TYPE_APPROX_BITRATE:
3680 ui->labelBitrate->setText(QString("&asymp; %1 kbps").arg(QString::number(displayValue)));
3681 break;
3682 case AbstractEncoderInfo::TYPE_QUALITY_LEVEL_INT:
3683 ui->labelBitrate->setText(tr("Quality Level %1").arg(QString::number(displayValue)));
3684 break;
3685 case AbstractEncoderInfo::TYPE_QUALITY_LEVEL_FLT:
3686 ui->labelBitrate->setText(tr("Quality Level %1").arg(QString().sprintf("%.2f", double(displayValue)/100.0)));
3687 break;
3688 case AbstractEncoderInfo::TYPE_COMPRESSION_LEVEL:
3689 ui->labelBitrate->setText(tr("Compression %1").arg(QString::number(displayValue)));
3690 break;
3691 case AbstractEncoderInfo::TYPE_UNCOMPRESSED:
3692 ui->labelBitrate->setText(tr("Uncompressed"));
3693 break;
3694 default:
3695 MUTILS_THROW("Unknown display value type encountered!");
3696 break;
3701 * Event for compression tab occurred
3703 void MainWindow::compressionTabEventOccurred(QWidget *sender, QEvent *event)
3705 static const QUrl helpUrl("http://lamexp.sourceforge.net/doc/FAQ.html#054010d9");
3707 if((sender == ui->labelCompressionHelp) && (event->type() == QEvent::MouseButtonPress))
3709 QDesktopServices::openUrl(helpUrl);
3711 else if((sender == ui->labelResetEncoders) && (event->type() == QEvent::MouseButtonPress))
3713 PLAY_SOUND_OPTIONAL("blast", true);
3714 EncoderRegistry::resetAllEncoders(m_settings);
3715 m_settings->compressionEncoder(SettingsModel::MP3Encoder);
3716 ui->radioButtonEncoderMP3->setChecked(true);
3717 QTimer::singleShot(0, this, SLOT(updateEncoder()));
3721 // =========================================================
3722 // Advanced option slots
3723 // =========================================================
3726 * Lame algorithm quality changed
3728 void MainWindow::updateLameAlgoQuality(int value)
3730 QString text;
3732 switch(value)
3734 case 3:
3735 text = tr("Best Quality (Slow)");
3736 break;
3737 case 2:
3738 text = tr("High Quality (Recommended)");
3739 break;
3740 case 1:
3741 text = tr("Acceptable Quality (Fast)");
3742 break;
3743 case 0:
3744 text = tr("Poor Quality (Very Fast)");
3745 break;
3748 if(!text.isEmpty())
3750 m_settings->lameAlgoQuality(value);
3751 ui->labelLameAlgoQuality->setText(text);
3754 bool warning = (value == 0), notice = (value == 3);
3755 ui->labelLameAlgoQualityWarning->setVisible(warning);
3756 ui->labelLameAlgoQualityWarningIcon->setVisible(warning);
3757 ui->labelLameAlgoQualityNotice->setVisible(notice);
3758 ui->labelLameAlgoQualityNoticeIcon->setVisible(notice);
3759 ui->labelLameAlgoQualitySpacer->setVisible(warning || notice);
3763 * Bitrate management endabled/disabled
3765 void MainWindow::bitrateManagementEnabledChanged(bool checked)
3767 m_settings->bitrateManagementEnabled(checked);
3771 * Minimum bitrate has changed
3773 void MainWindow::bitrateManagementMinChanged(int value)
3775 if(value > ui->spinBoxBitrateManagementMax->value())
3777 ui->spinBoxBitrateManagementMin->setValue(ui->spinBoxBitrateManagementMax->value());
3778 m_settings->bitrateManagementMinRate(ui->spinBoxBitrateManagementMax->value());
3780 else
3782 m_settings->bitrateManagementMinRate(value);
3787 * Maximum bitrate has changed
3789 void MainWindow::bitrateManagementMaxChanged(int value)
3791 if(value < ui->spinBoxBitrateManagementMin->value())
3793 ui->spinBoxBitrateManagementMax->setValue(ui->spinBoxBitrateManagementMin->value());
3794 m_settings->bitrateManagementMaxRate(ui->spinBoxBitrateManagementMin->value());
3796 else
3798 m_settings->bitrateManagementMaxRate(value);
3803 * Channel mode has changed
3805 void MainWindow::channelModeChanged(int value)
3807 if(value >= 0) m_settings->lameChannelMode(value);
3811 * Sampling rate has changed
3813 void MainWindow::samplingRateChanged(int value)
3815 if(value >= 0) m_settings->samplingRate(value);
3819 * Nero AAC 2-Pass mode changed
3821 void MainWindow::neroAAC2PassChanged(bool checked)
3823 m_settings->neroAACEnable2Pass(checked);
3827 * Nero AAC profile mode changed
3829 void MainWindow::neroAACProfileChanged(int value)
3831 if(value >= 0) m_settings->aacEncProfile(value);
3835 * Aften audio coding mode changed
3837 void MainWindow::aftenCodingModeChanged(int value)
3839 if(value >= 0) m_settings->aftenAudioCodingMode(value);
3843 * Aften DRC mode changed
3845 void MainWindow::aftenDRCModeChanged(int value)
3847 if(value >= 0) m_settings->aftenDynamicRangeCompression(value);
3851 * Aften exponent search size changed
3853 void MainWindow::aftenSearchSizeChanged(int value)
3855 if(value >= 0) m_settings->aftenExponentSearchSize(value);
3859 * Aften fast bit allocation changed
3861 void MainWindow::aftenFastAllocationChanged(bool checked)
3863 m_settings->aftenFastBitAllocation(checked);
3868 * Opus encoder settings changed
3870 void MainWindow::opusSettingsChanged(void)
3872 m_settings->opusFramesize(ui->comboBoxOpusFramesize->currentIndex());
3873 m_settings->opusComplexity(ui->spinBoxOpusComplexity->value());
3874 m_settings->opusDisableResample(ui->checkBoxOpusDisableResample->isChecked());
3878 * Normalization filter enabled changed
3880 void MainWindow::normalizationEnabledChanged(bool checked)
3882 m_settings->normalizationFilterEnabled(checked);
3883 normalizationDynamicChanged(ui->checkBoxNormalizationFilterDynamic->isChecked());
3887 * Dynamic normalization enabled changed
3889 void MainWindow::normalizationDynamicChanged(bool checked)
3891 ui->spinBoxNormalizationFilterSize->setEnabled(ui->checkBoxNormalizationFilterEnabled->isChecked() && checked);
3892 m_settings->normalizationFilterDynamic(checked);
3896 * Normalization max. volume changed
3898 void MainWindow::normalizationMaxVolumeChanged(double value)
3900 m_settings->normalizationFilterMaxVolume(static_cast<int>(value * 100.0));
3904 * Normalization equalization mode changed
3906 void MainWindow::normalizationCoupledChanged(bool checked)
3908 m_settings->normalizationFilterCoupled(checked);
3912 * Normalization filter size changed
3914 void MainWindow::normalizationFilterSizeChanged(int value)
3916 m_settings->normalizationFilterSize(value);
3920 * Normalization filter size editing finished
3922 void MainWindow::normalizationFilterSizeFinished(void)
3924 const int value = ui->spinBoxNormalizationFilterSize->value();
3925 if((value % 2) != 1)
3927 bool rnd = MUtils::parity(MUtils::next_rand_u32());
3928 ui->spinBoxNormalizationFilterSize->setValue(rnd ? value+1 : value-1);
3933 * Tone adjustment has changed (Bass)
3935 void MainWindow::toneAdjustBassChanged(double value)
3937 m_settings->toneAdjustBass(static_cast<int>(value * 100.0));
3938 ui->spinBoxToneAdjustBass->setPrefix((value > 0) ? "+" : QString());
3942 * Tone adjustment has changed (Treble)
3944 void MainWindow::toneAdjustTrebleChanged(double value)
3946 m_settings->toneAdjustTreble(static_cast<int>(value * 100.0));
3947 ui->spinBoxToneAdjustTreble->setPrefix((value > 0) ? "+" : QString());
3951 * Tone adjustment has been reset
3953 void MainWindow::toneAdjustTrebleReset(void)
3955 ui->spinBoxToneAdjustBass->setValue(m_settings->toneAdjustBassDefault());
3956 ui->spinBoxToneAdjustTreble->setValue(m_settings->toneAdjustTrebleDefault());
3957 toneAdjustBassChanged(ui->spinBoxToneAdjustBass->value());
3958 toneAdjustTrebleChanged(ui->spinBoxToneAdjustTreble->value());
3962 * Custom encoder parameters changed
3964 void MainWindow::customParamsChanged(void)
3966 ui->lineEditCustomParamLAME->setText(ui->lineEditCustomParamLAME->text().simplified());
3967 ui->lineEditCustomParamOggEnc->setText(ui->lineEditCustomParamOggEnc->text().simplified());
3968 ui->lineEditCustomParamNeroAAC->setText(ui->lineEditCustomParamNeroAAC->text().simplified());
3969 ui->lineEditCustomParamFLAC->setText(ui->lineEditCustomParamFLAC->text().simplified());
3970 ui->lineEditCustomParamAften->setText(ui->lineEditCustomParamAften->text().simplified());
3971 ui->lineEditCustomParamOpus->setText(ui->lineEditCustomParamOpus->text().simplified());
3973 bool customParamsUsed = false;
3974 if(!ui->lineEditCustomParamLAME->text().isEmpty()) customParamsUsed = true;
3975 if(!ui->lineEditCustomParamOggEnc->text().isEmpty()) customParamsUsed = true;
3976 if(!ui->lineEditCustomParamNeroAAC->text().isEmpty()) customParamsUsed = true;
3977 if(!ui->lineEditCustomParamFLAC->text().isEmpty()) customParamsUsed = true;
3978 if(!ui->lineEditCustomParamAften->text().isEmpty()) customParamsUsed = true;
3979 if(!ui->lineEditCustomParamOpus->text().isEmpty()) customParamsUsed = true;
3981 ui->labelCustomParamsIcon->setVisible(customParamsUsed);
3982 ui->labelCustomParamsText->setVisible(customParamsUsed);
3983 ui->labelCustomParamsSpacer->setVisible(customParamsUsed);
3985 EncoderRegistry::saveEncoderCustomParams(m_settings, SettingsModel::MP3Encoder, ui->lineEditCustomParamLAME->text());
3986 EncoderRegistry::saveEncoderCustomParams(m_settings, SettingsModel::VorbisEncoder, ui->lineEditCustomParamOggEnc->text());
3987 EncoderRegistry::saveEncoderCustomParams(m_settings, SettingsModel::AACEncoder, ui->lineEditCustomParamNeroAAC->text());
3988 EncoderRegistry::saveEncoderCustomParams(m_settings, SettingsModel::FLACEncoder, ui->lineEditCustomParamFLAC->text());
3989 EncoderRegistry::saveEncoderCustomParams(m_settings, SettingsModel::AC3Encoder, ui->lineEditCustomParamAften->text());
3990 EncoderRegistry::saveEncoderCustomParams(m_settings, SettingsModel::OpusEncoder, ui->lineEditCustomParamOpus->text());
3994 * One of the rename buttons has been clicked
3996 void MainWindow::renameButtonClicked(bool checked)
3998 if(QPushButton *const button = dynamic_cast<QPushButton*>(QObject::sender()))
4000 QWidget *pages[] = { ui->pageRename_Rename, ui->pageRename_RegExp, ui->pageRename_FileEx };
4001 QPushButton *buttons[] = { ui->buttonRename_Rename, ui->buttonRename_RegExp, ui->buttonRename_FileEx };
4002 for(int i = 0; i < 3; i++)
4004 const bool match = (button == buttons[i]);
4005 buttons[i]->setChecked(match);
4006 if(match && checked) ui->stackedWidget->setCurrentWidget(pages[i]);
4012 * Rename output files enabled changed
4014 void MainWindow::renameOutputEnabledChanged(const bool &checked)
4016 m_settings->renameFiles_renameEnabled(checked);
4020 * Rename output files patterm changed
4022 void MainWindow::renameOutputPatternChanged(void)
4024 QString temp = ui->lineEditRenamePattern->text().simplified();
4025 ui->lineEditRenamePattern->setText(temp.isEmpty() ? m_settings->renameFiles_renamePatternDefault() : temp);
4026 m_settings->renameFiles_renamePattern(ui->lineEditRenamePattern->text());
4030 * Rename output files patterm changed
4032 void MainWindow::renameOutputPatternChanged(const QString &text, const bool &silent)
4034 QString pattern(text.simplified());
4036 pattern.replace("<BaseName>", "The_White_Stripes_-_Fell_In_Love_With_A_Girl", Qt::CaseInsensitive);
4037 pattern.replace("<TrackNo>", "04", Qt::CaseInsensitive);
4038 pattern.replace("<Title>", "Fell In Love With A Girl", Qt::CaseInsensitive);
4039 pattern.replace("<Artist>", "The White Stripes", Qt::CaseInsensitive);
4040 pattern.replace("<Album>", "White Blood Cells", Qt::CaseInsensitive);
4041 pattern.replace("<Year>", "2001", Qt::CaseInsensitive);
4042 pattern.replace("<Comment>", "Encoded by LameXP", Qt::CaseInsensitive);
4044 const QString patternClean = MUtils::clean_file_name(pattern);
4046 if(pattern.compare(patternClean))
4048 if(ui->lineEditRenamePattern->palette().color(QPalette::Text) != Qt::red)
4050 if(!silent) MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
4051 SET_TEXT_COLOR(ui->lineEditRenamePattern, Qt::red);
4054 else
4056 if(ui->lineEditRenamePattern->palette() != QPalette())
4058 if(!silent) MUtils::Sound::beep(MUtils::Sound::BEEP_NFO);
4059 ui->lineEditRenamePattern->setPalette(QPalette());
4063 ui->labelRanameExample->setText(patternClean);
4067 * Regular expression enabled changed
4069 void MainWindow::renameRegExpEnabledChanged(const bool &checked)
4071 m_settings->renameFiles_regExpEnabled(checked);
4075 * Regular expression value has changed
4077 void MainWindow::renameRegExpValueChanged(void)
4079 const QString search = ui->lineEditRenameRegExp_Search->text() .trimmed();
4080 const QString replace = ui->lineEditRenameRegExp_Replace->text().simplified();
4081 ui->lineEditRenameRegExp_Search ->setText(search.isEmpty() ? m_settings->renameFiles_regExpSearchDefault() : search);
4082 ui->lineEditRenameRegExp_Replace->setText(replace.isEmpty() ? m_settings->renameFiles_regExpReplaceDefault() : replace);
4083 m_settings->renameFiles_regExpSearch (ui->lineEditRenameRegExp_Search ->text());
4084 m_settings->renameFiles_regExpReplace(ui->lineEditRenameRegExp_Replace->text());
4088 * Regular expression search pattern has changed
4090 void MainWindow::renameRegExpSearchChanged(const QString &text, const bool &silent)
4092 const QString pattern(text.trimmed());
4094 if((!pattern.isEmpty()) && (!QRegExp(pattern.trimmed()).isValid()))
4096 if(ui->lineEditRenameRegExp_Search->palette().color(QPalette::Text) != Qt::red)
4098 if(!silent) MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
4099 SET_TEXT_COLOR(ui->lineEditRenameRegExp_Search, Qt::red);
4102 else
4104 if(ui->lineEditRenameRegExp_Search->palette() != QPalette())
4106 if(!silent) MUtils::Sound::beep(MUtils::Sound::BEEP_NFO);
4107 ui->lineEditRenameRegExp_Search->setPalette(QPalette());
4111 renameRegExpReplaceChanged(ui->lineEditRenameRegExp_Replace->text(), silent);
4115 * Regular expression replacement string changed
4117 void MainWindow::renameRegExpReplaceChanged(const QString &text, const bool &silent)
4119 QString replacement(text.simplified());
4120 const QString search(ui->lineEditRenameRegExp_Search->text().trimmed());
4122 if(!search.isEmpty())
4124 const QRegExp regexp(search);
4125 if(regexp.isValid())
4127 const int count = regexp.captureCount();
4128 const QString blank;
4129 for(int i = 0; i < count; i++)
4131 replacement.replace(QString("\\%0").arg(QString::number(i+1)), blank);
4136 if(replacement.compare(MUtils::clean_file_name(replacement)))
4138 if(ui->lineEditRenameRegExp_Replace->palette().color(QPalette::Text) != Qt::red)
4140 if(!silent) MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
4141 SET_TEXT_COLOR(ui->lineEditRenameRegExp_Replace, Qt::red);
4144 else
4146 if(ui->lineEditRenameRegExp_Replace->palette() != QPalette())
4148 if(!silent) MUtils::Sound::beep(MUtils::Sound::BEEP_NFO);
4149 ui->lineEditRenameRegExp_Replace->setPalette(QPalette());
4155 * Show list of rename macros
4157 void MainWindow::showRenameMacros(const QString &text)
4159 if(text.compare("reset", Qt::CaseInsensitive) == 0)
4161 ui->lineEditRenamePattern->setText(m_settings->renameFiles_renamePatternDefault());
4162 return;
4165 if(text.compare("regexp", Qt::CaseInsensitive) == 0)
4167 MUtils::OS::shell_open(this, "http://www.regular-expressions.info/quickstart.html");
4168 return;
4171 const QString format = QString("<tr><td><tt>&lt;%1&gt;</tt></td><td>&nbsp;&nbsp;</td><td>%2</td></tr>");
4173 QString message = QString("<table>");
4174 message += QString(format).arg("BaseName", tr("File name without extension"));
4175 message += QString(format).arg("TrackNo", tr("Track number with leading zero"));
4176 message += QString(format).arg("Title", tr("Track title"));
4177 message += QString(format).arg("Artist", tr("Artist name"));
4178 message += QString(format).arg("Album", tr("Album name"));
4179 message += QString(format).arg("Year", tr("Year with (at least) four digits"));
4180 message += QString(format).arg("Comment", tr("Comment"));
4181 message += "</table><br><br>";
4182 message += QString("%1<br>").arg(tr("Characters forbidden in file names:"));
4183 message += "<b><tt>\\ / : * ? &lt; &gt; |<br>";
4185 QMessageBox::information(this, tr("Rename Macros"), message, tr("Discard"));
4188 void MainWindow::fileExtAddButtonClicked(void)
4190 if(FileExtsModel *const model = dynamic_cast<FileExtsModel*>(ui->tableViewFileExts->model()))
4192 model->addOverwrite(this);
4196 void MainWindow::fileExtRemoveButtonClicked(void)
4198 if(FileExtsModel *const model = dynamic_cast<FileExtsModel*>(ui->tableViewFileExts->model()))
4200 const QModelIndex selected = ui->tableViewFileExts->currentIndex();
4201 if(selected.isValid())
4203 model->removeOverwrite(selected);
4205 else
4207 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
4212 void MainWindow::fileExtModelChanged(void)
4214 if(FileExtsModel *const model = dynamic_cast<FileExtsModel*>(ui->tableViewFileExts->model()))
4216 m_settings->renameFiles_fileExtension(model->exportItems());
4220 void MainWindow::forceStereoDownmixEnabledChanged(bool checked)
4222 m_settings->forceStereoDownmix(checked);
4226 * Maximum number of instances changed
4228 void MainWindow::updateMaximumInstances(int value)
4230 ui->labelMaxInstances->setText(tr("%n Instance(s)", "", value));
4231 m_settings->maximumInstances(ui->checkBoxAutoDetectInstances->isChecked() ? NULL : value);
4235 * Auto-detect number of instances
4237 void MainWindow::autoDetectInstancesChanged(bool checked)
4239 m_settings->maximumInstances(checked ? NULL : ui->sliderMaxInstances->value());
4243 * Browse for custom TEMP folder button clicked
4245 void MainWindow::browseCustomTempFolderButtonClicked(void)
4247 QString newTempFolder;
4249 if(MUtils::GUI::themes_enabled())
4251 newTempFolder = QFileDialog::getExistingDirectory(this, QString(), m_settings->customTempPath());
4253 else
4255 QFileDialog dialog(this);
4256 dialog.setFileMode(QFileDialog::DirectoryOnly);
4257 dialog.setDirectory(m_settings->customTempPath());
4258 if(dialog.exec())
4260 newTempFolder = dialog.selectedFiles().first();
4264 if(!newTempFolder.isEmpty())
4266 QFile writeTest(QString("%1/~%2.tmp").arg(newTempFolder, MUtils::next_rand_str()));
4267 if(writeTest.open(QIODevice::ReadWrite))
4269 writeTest.remove();
4270 ui->lineEditCustomTempFolder->setText(QDir::toNativeSeparators(newTempFolder));
4272 else
4274 QMessageBox::warning(this, tr("Access Denied"), tr("Cannot write to the selected directory. Please choose another directory!"));
4280 * Custom TEMP folder changed
4282 void MainWindow::customTempFolderChanged(const QString &text)
4284 m_settings->customTempPath(QDir::fromNativeSeparators(text));
4288 * Use custom TEMP folder option changed
4290 void MainWindow::useCustomTempFolderChanged(bool checked)
4292 m_settings->customTempPathEnabled(!checked);
4296 * Help for custom parameters was requested
4298 void MainWindow::customParamsHelpRequested(QWidget *obj, QEvent *event)
4300 if(event->type() != QEvent::MouseButtonRelease)
4302 return;
4305 if(QMouseEvent *mouseEvent = dynamic_cast<QMouseEvent*>(event))
4307 QPoint pos = mouseEvent->pos();
4308 if(!(pos.x() <= obj->width() && pos.y() <= obj->height() && pos.x() >= 0 && pos.y() >= 0 && mouseEvent->button() != Qt::MidButton))
4310 return;
4314 if(obj == ui->helpCustomParamLAME) showCustomParamsHelpScreen("lame.exe", "--longhelp");
4315 else if(obj == ui->helpCustomParamOggEnc) showCustomParamsHelpScreen("oggenc2.exe", "--help");
4316 else if(obj == ui->helpCustomParamNeroAAC)
4318 switch(EncoderRegistry::getAacEncoder())
4320 case SettingsModel::AAC_ENCODER_QAAC: showCustomParamsHelpScreen("qaac64.exe|qaac.exe", "--help"); break;
4321 case SettingsModel::AAC_ENCODER_FHG : showCustomParamsHelpScreen("fhgaacenc.exe", "" ); break;
4322 case SettingsModel::AAC_ENCODER_FDK : showCustomParamsHelpScreen("fdkaac.exe", "--help"); break;
4323 case SettingsModel::AAC_ENCODER_NERO: showCustomParamsHelpScreen("neroAacEnc.exe", "-help" ); break;
4324 default: MUtils::Sound::beep(MUtils::Sound::BEEP_ERR); break;
4327 else if(obj == ui->helpCustomParamFLAC) showCustomParamsHelpScreen("flac.exe", "--help");
4328 else if(obj == ui->helpCustomParamAften) showCustomParamsHelpScreen("aften.exe", "-h" );
4329 else if(obj == ui->helpCustomParamOpus) showCustomParamsHelpScreen("opusenc.exe", "--help");
4330 else MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
4334 * Show help for custom parameters
4336 void MainWindow::showCustomParamsHelpScreen(const QString &toolName, const QString &command)
4338 const QStringList toolNames = toolName.split('|', QString::SkipEmptyParts);
4339 QString binary;
4340 for(QStringList::ConstIterator iter = toolNames.constBegin(); iter != toolNames.constEnd(); iter++)
4342 if(lamexp_tools_check(*iter))
4344 binary = lamexp_tools_lookup(*iter);
4345 break;
4349 if(binary.isEmpty())
4351 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
4352 qWarning("customParamsHelpRequested: Binary could not be found!");
4353 return;
4356 QProcess process;
4357 MUtils::init_process(process, QFileInfo(binary).absolutePath());
4359 process.start(binary, command.isEmpty() ? QStringList() : QStringList() << command);
4361 qApp->setOverrideCursor(QCursor(Qt::WaitCursor));
4363 if(process.waitForStarted(15000))
4365 qApp->processEvents();
4366 process.waitForFinished(15000);
4369 if(process.state() != QProcess::NotRunning)
4371 process.kill();
4372 process.waitForFinished(-1);
4375 qApp->restoreOverrideCursor();
4376 QStringList output; bool spaceFlag = true;
4378 while(process.canReadLine())
4380 QString temp = QString::fromUtf8(process.readLine());
4381 TRIM_STRING_RIGHT(temp);
4382 if(temp.isEmpty())
4384 if(!spaceFlag) { output << temp; spaceFlag = true; }
4386 else
4388 output << temp; spaceFlag = false;
4392 if(output.count() < 1)
4394 qWarning("Empty output, cannot show help screen!");
4395 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
4398 WidgetHideHelper hiderHelper(m_dropBox.data());
4399 QScopedPointer<LogViewDialog> dialog(new LogViewDialog(this));
4400 dialog->exec(output);
4404 * File overwrite mode has changed
4407 void MainWindow::overwriteModeChanged(int id)
4409 if((id == SettingsModel::Overwrite_Replaces) && (m_settings->overwriteMode() != SettingsModel::Overwrite_Replaces))
4411 if(QMessageBox::warning(this, tr("Overwrite Mode"), tr("Warning: This mode may overwrite existing files with no way to revert!"), tr("Continue"), tr("Revert"), QString(), 1) != 0)
4413 ui->radioButtonOverwriteModeKeepBoth->setChecked(m_settings->overwriteMode() == SettingsModel::Overwrite_KeepBoth);
4414 ui->radioButtonOverwriteModeSkipFile->setChecked(m_settings->overwriteMode() == SettingsModel::Overwrite_SkipFile);
4415 return;
4419 m_settings->overwriteMode(id);
4423 * Keep original date/time opertion changed
4425 void MainWindow::keepOriginalDateTimeChanged(bool checked)
4427 m_settings->keepOriginalDataTime(checked);
4431 * Reset all advanced options to their defaults
4433 void MainWindow::resetAdvancedOptionsButtonClicked(void)
4435 PLAY_SOUND_OPTIONAL("blast", true);
4437 ui->sliderLameAlgoQuality ->setValue(m_settings->lameAlgoQualityDefault());
4438 ui->spinBoxBitrateManagementMin ->setValue(m_settings->bitrateManagementMinRateDefault());
4439 ui->spinBoxBitrateManagementMax ->setValue(m_settings->bitrateManagementMaxRateDefault());
4440 ui->spinBoxNormalizationFilterPeak->setValue(static_cast<double>(m_settings->normalizationFilterMaxVolumeDefault()) / 100.0);
4441 ui->spinBoxNormalizationFilterSize->setValue(m_settings->normalizationFilterSizeDefault());
4442 ui->spinBoxToneAdjustBass ->setValue(static_cast<double>(m_settings->toneAdjustBassDefault()) / 100.0);
4443 ui->spinBoxToneAdjustTreble ->setValue(static_cast<double>(m_settings->toneAdjustTrebleDefault()) / 100.0);
4444 ui->spinBoxAftenSearchSize ->setValue(m_settings->aftenExponentSearchSizeDefault());
4445 ui->spinBoxOpusComplexity ->setValue(m_settings->opusComplexityDefault());
4446 ui->comboBoxMP3ChannelMode ->setCurrentIndex(m_settings->lameChannelModeDefault());
4447 ui->comboBoxSamplingRate ->setCurrentIndex(m_settings->samplingRateDefault());
4448 ui->comboBoxAACProfile ->setCurrentIndex(m_settings->aacEncProfileDefault());
4449 ui->comboBoxAftenCodingMode ->setCurrentIndex(m_settings->aftenAudioCodingModeDefault());
4450 ui->comboBoxAftenDRCMode ->setCurrentIndex(m_settings->aftenDynamicRangeCompressionDefault());
4451 ui->comboBoxOpusFramesize ->setCurrentIndex(m_settings->opusFramesizeDefault());
4453 SET_CHECKBOX_STATE(ui->checkBoxBitrateManagement, m_settings->bitrateManagementEnabledDefault());
4454 SET_CHECKBOX_STATE(ui->checkBoxNeroAAC2PassMode, m_settings->neroAACEnable2PassDefault());
4455 SET_CHECKBOX_STATE(ui->checkBoxNormalizationFilterEnabled, m_settings->normalizationFilterEnabledDefault());
4456 SET_CHECKBOX_STATE(ui->checkBoxNormalizationFilterDynamic, m_settings->normalizationFilterDynamicDefault());
4457 SET_CHECKBOX_STATE(ui->checkBoxNormalizationFilterCoupled, m_settings->normalizationFilterCoupledDefault());
4458 SET_CHECKBOX_STATE(ui->checkBoxAutoDetectInstances, (m_settings->maximumInstancesDefault() < 1));
4459 SET_CHECKBOX_STATE(ui->checkBoxUseSystemTempFolder, (!m_settings->customTempPathEnabledDefault()));
4460 SET_CHECKBOX_STATE(ui->checkBoxAftenFastAllocation, m_settings->aftenFastBitAllocationDefault());
4461 SET_CHECKBOX_STATE(ui->checkBoxRename_Rename, m_settings->renameFiles_renameEnabledDefault());
4462 SET_CHECKBOX_STATE(ui->checkBoxRename_RegExp, m_settings->renameFiles_regExpEnabledDefault());
4463 SET_CHECKBOX_STATE(ui->checkBoxForceStereoDownmix, m_settings->forceStereoDownmixDefault());
4464 SET_CHECKBOX_STATE(ui->checkBoxOpusDisableResample, m_settings->opusDisableResampleDefault());
4465 SET_CHECKBOX_STATE(ui->checkBoxKeepOriginalDateTime, m_settings->keepOriginalDataTimeDefault());
4467 ui->lineEditCustomParamLAME ->setText(m_settings->customParametersLAMEDefault());
4468 ui->lineEditCustomParamOggEnc ->setText(m_settings->customParametersOggEncDefault());
4469 ui->lineEditCustomParamNeroAAC ->setText(m_settings->customParametersAacEncDefault());
4470 ui->lineEditCustomParamFLAC ->setText(m_settings->customParametersFLACDefault());
4471 ui->lineEditCustomParamOpus ->setText(m_settings->customParametersOpusEncDefault());
4472 ui->lineEditCustomTempFolder ->setText(QDir::toNativeSeparators(m_settings->customTempPathDefault()));
4473 ui->lineEditRenamePattern ->setText(m_settings->renameFiles_renamePatternDefault());
4474 ui->lineEditRenameRegExp_Search ->setText(m_settings->renameFiles_regExpSearchDefault());
4475 ui->lineEditRenameRegExp_Replace->setText(m_settings->renameFiles_regExpReplaceDefault());
4477 if(m_settings->overwriteModeDefault() == SettingsModel::Overwrite_KeepBoth) ui->radioButtonOverwriteModeKeepBoth->click();
4478 if(m_settings->overwriteModeDefault() == SettingsModel::Overwrite_SkipFile) ui->radioButtonOverwriteModeSkipFile->click();
4479 if(m_settings->overwriteModeDefault() == SettingsModel::Overwrite_Replaces) ui->radioButtonOverwriteModeReplaces->click();
4481 if(FileExtsModel *const model = dynamic_cast<FileExtsModel*>(ui->tableViewFileExts->model()))
4483 model->importItems(m_settings->renameFiles_fileExtensionDefault());
4486 ui->scrollArea->verticalScrollBar()->setValue(0);
4487 ui->buttonRename_Rename->click();
4488 customParamsChanged();
4489 renameOutputPatternChanged();
4490 renameRegExpValueChanged();
4493 // =========================================================
4494 // Multi-instance handling slots
4495 // =========================================================
4498 * Other instance detected
4500 void MainWindow::notifyOtherInstance(void)
4502 if(!(BANNER_VISIBLE))
4504 QMessageBox msgBox(QMessageBox::Warning, tr("Already Running"), tr("LameXP is already running, please use the running instance!"), QMessageBox::NoButton, this, Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowStaysOnTopHint);
4505 msgBox.exec();
4510 * Add file from another instance
4512 void MainWindow::addFileDelayed(const QString &filePath, bool tryASAP)
4514 if(tryASAP && !m_delayedFileTimer->isActive())
4516 qDebug("Received file: %s", MUTILS_UTF8(filePath));
4517 m_delayedFileList->append(filePath);
4518 QTimer::singleShot(0, this, SLOT(handleDelayedFiles()));
4521 m_delayedFileTimer->stop();
4522 qDebug("Received file: %s", MUTILS_UTF8(filePath));
4523 m_delayedFileList->append(filePath);
4524 m_delayedFileTimer->start(5000);
4528 * Add files from another instance
4530 void MainWindow::addFilesDelayed(const QStringList &filePaths, bool tryASAP)
4532 if(tryASAP && (!m_delayedFileTimer->isActive()))
4534 qDebug("Received %d file(s).", filePaths.count());
4535 m_delayedFileList->append(filePaths);
4536 QTimer::singleShot(0, this, SLOT(handleDelayedFiles()));
4538 else
4540 m_delayedFileTimer->stop();
4541 qDebug("Received %d file(s).", filePaths.count());
4542 m_delayedFileList->append(filePaths);
4543 m_delayedFileTimer->start(5000);
4548 * Add folder from another instance
4550 void MainWindow::addFolderDelayed(const QString &folderPath, bool recursive)
4552 if(!(BANNER_VISIBLE))
4554 addFolder(folderPath, recursive, true);
4558 // =========================================================
4559 // Misc slots
4560 // =========================================================
4563 * Restore the override cursor
4565 void MainWindow::restoreCursor(void)
4567 QApplication::restoreOverrideCursor();