1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2014 LoRd_MuldeR <MuldeR2@GMX.de>
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; either version 2 of the License, or
8 // (at your option) any later version, but always including the *additional*
9 // restrictions defined in the "License.txt" file.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License along
17 // with this program; if not, write to the Free Software Foundation, Inc.,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 // http://www.gnu.org/licenses/gpl-2.0.txt
21 ///////////////////////////////////////////////////////////////////////////////
23 #include "Dialog_MainWindow.h"
26 #include "UIC_MainWindow.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 "WinSevenTaskbar.h"
44 #include "Registry_Encoder.h"
45 #include "Registry_Decoder.h"
46 #include "Encoder_Abstract.h"
47 #include "ShellIntegration.h"
48 #include "CustomEventFilter.h"
51 #include <MUtils/Global.h>
52 #include <MUtils/OSSupport.h>
53 #include <MUtils/GUI.h>
54 #include <MUtils/Exception.h>
55 #include <MUtils/Version.h>
58 #include <QMessageBox>
60 #include <QDesktopWidget>
62 #include <QFileDialog>
63 #include <QInputDialog>
64 #include <QFileSystemModel>
65 #include <QDesktopServices>
67 #include <QPlastiqueStyle>
68 #include <QCleanlooksStyle>
69 #include <QWindowsVistaStyle>
70 #include <QWindowsStyle>
72 #include <QDragEnterEvent>
76 #include <QProcessEnvironment>
77 #include <QCryptographicHash>
78 #include <QTranslator>
82 ////////////////////////////////////////////////////////////
84 ////////////////////////////////////////////////////////////
86 #define BANNER_VISIBLE ((m_banner != NULL) && m_banner->isVisible())
88 #define INIT_BANNER() do \
90 if(m_banner == NULL) \
92 m_banner = new WorkingBanner(this); \
97 #define SHOW_BANNER(TXT) do \
100 m_banner->show((TXT)); \
104 #define SHOW_BANNER_ARG(TXT, ARG) do \
107 m_banner->show((TXT), (ARG)); \
112 #define SHOW_BANNER_CONDITIONALLY(FLAG, TEST, TXT) do \
114 if((!(FLAG)) && ((TEST))) \
117 m_banner->show((TXT)); \
123 #define ABORT_IF_BUSY do \
125 if(BANNER_VISIBLE || m_delayedFileTimer->isActive() || (QApplication::activeModalWidget() != NULL)) \
127 lamexp_beep(lamexp_beep_warning); \
133 #define SET_TEXT_COLOR(WIDGET, COLOR) do \
135 QPalette _palette = WIDGET->palette(); \
136 _palette.setColor(QPalette::WindowText, (COLOR)); \
137 _palette.setColor(QPalette::Text, (COLOR)); \
138 WIDGET->setPalette(_palette); \
142 #define SET_FONT_BOLD(WIDGET,BOLD) do \
144 QFont _font = WIDGET->font(); \
145 _font.setBold(BOLD); \
146 WIDGET->setFont(_font); \
150 #define TEMP_HIDE_DROPBOX(CMD) do \
152 bool _dropBoxVisible = m_dropBox->isVisible(); \
153 if(_dropBoxVisible) m_dropBox->hide(); \
154 do { CMD } while(0); \
155 if(_dropBoxVisible) m_dropBox->show(); \
159 #define SET_MODEL(VIEW, MODEL) do \
161 QItemSelectionModel *_tmp = (VIEW)->selectionModel(); \
162 (VIEW)->setModel(MODEL); \
163 MUTILS_DELETE(_tmp); \
167 #define SET_CHECKBOX_STATE(CHCKBX, STATE) do \
169 if((CHCKBX)->isChecked() != (STATE)) \
173 if((CHCKBX)->isChecked() != (STATE)) \
175 qWarning("Warning: Failed to set checkbox " #CHCKBX " state!"); \
180 #define TRIM_STRING_RIGHT(STR) do \
182 while((STR.length() > 0) && STR[STR.length()-1].isSpace()) STR.chop(1); \
186 #define MAKE_TRANSPARENT(WIDGET, FLAG) do \
188 QPalette _p = (WIDGET)->palette(); \
189 _p.setColor(QPalette::Background, Qt::transparent); \
190 (WIDGET)->setPalette(FLAG ? _p : QPalette()); \
194 #define WITH_BLOCKED_SIGNALS(WIDGET, CMD, ...) do \
196 const bool _flag = (WIDGET)->blockSignals(true); \
197 (WIDGET)->CMD(__VA_ARGS__); \
198 if(!(_flag)) { (WIDGET)->blockSignals(false); } \
202 #define PLAY_SOUND_OPTIONAL(NAME, ASYNC) do \
204 if(m_settings->soundsEnabled()) lamexp_play_sound((NAME), (ASYNC)); \
208 #define SHOW_CORNER_WIDGET(FLAG) do \
210 if(QWidget *cornerWidget = ui->menubar->cornerWidget()) \
212 cornerWidget->setVisible((FLAG)); \
217 #define LINK(URL) QString("<a href=\"%1\">%2</a>").arg(URL).arg(QString(URL).replace("-", "−"))
218 #define FSLINK(PATH) QString("<a href=\"file:///%1\">%2</a>").arg(PATH).arg(QString(PATH).replace("-", "−"))
219 #define CENTER_CURRENT_OUTPUT_FOLDER_DELAYED QTimer::singleShot(125, this, SLOT(centerOutputFolderModel()))
221 static const unsigned int IDM_ABOUTBOX = 0xEFF0;
222 static const char *g_hydrogen_audio_url = "http://wiki.hydrogenaud.io/index.php?title=Main_Page";
224 ////////////////////////////////////////////////////////////
226 ////////////////////////////////////////////////////////////
228 MainWindow::MainWindow(FileListModel *fileListModel, AudioFileModel_MetaInfo *metaInfo, SettingsModel *settingsModel, QWidget *parent)
231 ui(new Ui::MainWindow),
232 m_fileListModel(fileListModel),
233 m_metaData(metaInfo),
234 m_settings(settingsModel),
235 m_fileSystemModel(NULL),
238 m_firstTimeShown(true),
239 m_outputFolderViewCentering(false),
240 m_outputFolderViewInitCounter(0)
242 //Init the dialog, from the .ui file
244 setWindowFlags(windowFlags() ^ Qt::WindowMaximizeButtonHint);
247 MUtils::GUI::set_window_icon(this, lamexp_app_icon(), true);
249 //Register meta types
250 qRegisterMetaType<AudioFileModel>("AudioFileModel");
252 //Enabled main buttons
253 connect(ui->buttonAbout, SIGNAL(clicked()), this, SLOT(aboutButtonClicked()));
254 connect(ui->buttonStart, SIGNAL(clicked()), this, SLOT(encodeButtonClicked()));
255 connect(ui->buttonQuit, SIGNAL(clicked()), this, SLOT(closeButtonClicked()));
258 ui->tabWidget->setCurrentIndex(0);
259 connect(ui->tabWidget, SIGNAL(currentChanged(int)), this, SLOT(tabPageChanged(int)));
262 lamexp_append_sysmenu(this, IDM_ABOUTBOX, "About...");
264 //Setup corner widget
265 QLabel *cornerWidget = new QLabel(ui->menubar);
266 m_evenFilterCornerWidget = new CustomEventFilter;
267 cornerWidget->setText("N/A");
268 cornerWidget->setFixedHeight(ui->menubar->height());
269 cornerWidget->setCursor(QCursor(Qt::PointingHandCursor));
270 cornerWidget->hide();
271 cornerWidget->installEventFilter(m_evenFilterCornerWidget);
272 connect(m_evenFilterCornerWidget, SIGNAL(eventOccurred(QWidget*, QEvent*)), this, SLOT(cornerWidgetEventOccurred(QWidget*, QEvent*)));
273 ui->menubar->setCornerWidget(cornerWidget);
275 //--------------------------------
276 // Setup "Source" tab
277 //--------------------------------
279 ui->sourceFileView->setModel(m_fileListModel);
280 ui->sourceFileView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
281 ui->sourceFileView->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);
282 ui->sourceFileView->setContextMenuPolicy(Qt::CustomContextMenu);
283 ui->sourceFileView->viewport()->installEventFilter(this);
284 m_dropNoteLabel = new QLabel(ui->sourceFileView);
285 m_dropNoteLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
286 SET_FONT_BOLD(m_dropNoteLabel, true);
287 SET_TEXT_COLOR(m_dropNoteLabel, Qt::darkGray);
288 m_sourceFilesContextMenu = new QMenu();
289 m_showDetailsContextAction = m_sourceFilesContextMenu->addAction(QIcon(":/icons/zoom.png"), "N/A");
290 m_previewContextAction = m_sourceFilesContextMenu->addAction(QIcon(":/icons/sound.png"), "N/A");
291 m_findFileContextAction = m_sourceFilesContextMenu->addAction(QIcon(":/icons/folder_go.png"), "N/A");
292 m_sourceFilesContextMenu->addSeparator();
293 m_exportCsvContextAction = m_sourceFilesContextMenu->addAction(QIcon(":/icons/table_save.png"), "N/A");
294 m_importCsvContextAction = m_sourceFilesContextMenu->addAction(QIcon(":/icons/folder_table.png"), "N/A");
295 SET_FONT_BOLD(m_showDetailsContextAction, true);
297 connect(ui->buttonAddFiles, SIGNAL(clicked()), this, SLOT(addFilesButtonClicked()));
298 connect(ui->buttonRemoveFile, SIGNAL(clicked()), this, SLOT(removeFileButtonClicked()));
299 connect(ui->buttonClearFiles, SIGNAL(clicked()), this, SLOT(clearFilesButtonClicked()));
300 connect(ui->buttonFileUp, SIGNAL(clicked()), this, SLOT(fileUpButtonClicked()));
301 connect(ui->buttonFileDown, SIGNAL(clicked()), this, SLOT(fileDownButtonClicked()));
302 connect(ui->buttonShowDetails, SIGNAL(clicked()), this, SLOT(showDetailsButtonClicked()));
303 connect(m_fileListModel, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(sourceModelChanged()));
304 connect(m_fileListModel, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(sourceModelChanged()));
305 connect(m_fileListModel, SIGNAL(modelReset()), this, SLOT(sourceModelChanged()));
306 connect(ui->sourceFileView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(sourceFilesContextMenu(QPoint)));
307 connect(ui->sourceFileView->verticalScrollBar(), SIGNAL(sliderMoved(int)), this, SLOT(sourceFilesScrollbarMoved(int)));
308 connect(ui->sourceFileView->verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(sourceFilesScrollbarMoved(int)));
309 connect(m_showDetailsContextAction, SIGNAL(triggered(bool)), this, SLOT(showDetailsButtonClicked()));
310 connect(m_previewContextAction, SIGNAL(triggered(bool)), this, SLOT(previewContextActionTriggered()));
311 connect(m_findFileContextAction, SIGNAL(triggered(bool)), this, SLOT(findFileContextActionTriggered()));
312 connect(m_exportCsvContextAction, SIGNAL(triggered(bool)), this, SLOT(exportCsvContextActionTriggered()));
313 connect(m_importCsvContextAction, SIGNAL(triggered(bool)), this, SLOT(importCsvContextActionTriggered()));
315 //--------------------------------
316 // Setup "Output" tab
317 //--------------------------------
319 ui->outputFolderView->setHeaderHidden(true);
320 ui->outputFolderView->setAnimated(false);
321 ui->outputFolderView->setMouseTracking(false);
322 ui->outputFolderView->setContextMenuPolicy(Qt::CustomContextMenu);
323 ui->outputFolderView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
325 m_evenFilterOutputFolderMouse = new CustomEventFilter;
326 ui->outputFoldersGoUpLabel->installEventFilter(m_evenFilterOutputFolderMouse);
327 ui->outputFoldersEditorLabel->installEventFilter(m_evenFilterOutputFolderMouse);
328 ui->outputFoldersFovoritesLabel->installEventFilter(m_evenFilterOutputFolderMouse);
329 ui->outputFolderLabel->installEventFilter(m_evenFilterOutputFolderMouse);
331 m_evenFilterOutputFolderView = new CustomEventFilter;
332 ui->outputFolderView->installEventFilter(m_evenFilterOutputFolderView);
334 SET_CHECKBOX_STATE(ui->saveToSourceFolderCheckBox, m_settings->outputToSourceDir());
335 ui->prependRelativePathCheckBox->setChecked(m_settings->prependRelativeSourcePath());
337 connect(ui->outputFolderView, SIGNAL(clicked(QModelIndex)), this, SLOT(outputFolderViewClicked(QModelIndex)));
338 connect(ui->outputFolderView, SIGNAL(activated(QModelIndex)), this, SLOT(outputFolderViewClicked(QModelIndex)));
339 connect(ui->outputFolderView, SIGNAL(pressed(QModelIndex)), this, SLOT(outputFolderViewClicked(QModelIndex)));
340 connect(ui->outputFolderView, SIGNAL(entered(QModelIndex)), this, SLOT(outputFolderViewMoved(QModelIndex)));
341 connect(ui->outputFolderView, SIGNAL(expanded(QModelIndex)), this, SLOT(outputFolderItemExpanded(QModelIndex)));
342 connect(ui->buttonMakeFolder, SIGNAL(clicked()), this, SLOT(makeFolderButtonClicked()));
343 connect(ui->buttonGotoHome, SIGNAL(clicked()), SLOT(gotoHomeFolderButtonClicked()));
344 connect(ui->buttonGotoDesktop, SIGNAL(clicked()), this, SLOT(gotoDesktopButtonClicked()));
345 connect(ui->buttonGotoMusic, SIGNAL(clicked()), this, SLOT(gotoMusicFolderButtonClicked()));
346 connect(ui->saveToSourceFolderCheckBox, SIGNAL(clicked()), this, SLOT(saveToSourceFolderChanged()));
347 connect(ui->prependRelativePathCheckBox, SIGNAL(clicked()), this, SLOT(prependRelativePathChanged()));
348 connect(ui->outputFolderEdit, SIGNAL(editingFinished()), this, SLOT(outputFolderEditFinished()));
349 connect(m_evenFilterOutputFolderMouse, SIGNAL(eventOccurred(QWidget*, QEvent*)), this, SLOT(outputFolderMouseEventOccurred(QWidget*, QEvent*)));
350 connect(m_evenFilterOutputFolderView, SIGNAL(eventOccurred(QWidget*, QEvent*)), this, SLOT(outputFolderViewEventOccurred(QWidget*, QEvent*)));
352 if(m_outputFolderContextMenu = new QMenu())
354 m_showFolderContextAction = m_outputFolderContextMenu->addAction(QIcon(":/icons/zoom.png"), "N/A");
355 m_goUpFolderContextAction = m_outputFolderContextMenu->addAction(QIcon(":/icons/folder_up.png"), "N/A");
356 m_outputFolderContextMenu->addSeparator();
357 m_refreshFolderContextAction = m_outputFolderContextMenu->addAction(QIcon(":/icons/arrow_refresh.png"), "N/A");
358 m_outputFolderContextMenu->setDefaultAction(m_showFolderContextAction);
359 connect(ui->outputFolderView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(outputFolderContextMenu(QPoint)));
360 connect(m_showFolderContextAction, SIGNAL(triggered(bool)), this, SLOT(showFolderContextActionTriggered()));
361 connect(m_refreshFolderContextAction, SIGNAL(triggered(bool)), this, SLOT(refreshFolderContextActionTriggered()));
362 connect(m_goUpFolderContextAction, SIGNAL(triggered(bool)), this, SLOT(goUpFolderContextActionTriggered()));
365 if(m_outputFolderFavoritesMenu = new QMenu())
367 m_addFavoriteFolderAction = m_outputFolderFavoritesMenu->addAction(QIcon(":/icons/add.png"), "N/A");
368 m_outputFolderFavoritesMenu->insertSeparator(m_addFavoriteFolderAction);
369 connect(m_addFavoriteFolderAction, SIGNAL(triggered(bool)), this, SLOT(addFavoriteFolderActionTriggered()));
372 ui->outputFolderEdit->setVisible(false);
373 if(m_outputFolderNoteBox = new QLabel(ui->outputFolderView))
375 m_outputFolderNoteBox->setAutoFillBackground(true);
376 m_outputFolderNoteBox->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
377 m_outputFolderNoteBox->setFrameShape(QFrame::StyledPanel);
378 SET_FONT_BOLD(m_outputFolderNoteBox, true);
379 m_outputFolderNoteBox->hide();
383 outputFolderViewClicked(QModelIndex());
386 //--------------------------------
387 // Setup "Meta Data" tab
388 //--------------------------------
390 m_metaInfoModel = new MetaInfoModel(m_metaData);
391 m_metaInfoModel->clearData();
392 m_metaInfoModel->setData(m_metaInfoModel->index(4, 1), m_settings->metaInfoPosition());
393 ui->metaDataView->setModel(m_metaInfoModel);
394 ui->metaDataView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
395 ui->metaDataView->verticalHeader()->hide();
396 ui->metaDataView->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);
397 SET_CHECKBOX_STATE(ui->writeMetaDataCheckBox, m_settings->writeMetaTags());
398 ui->generatePlaylistCheckBox->setChecked(m_settings->createPlaylist());
399 connect(ui->buttonEditMeta, SIGNAL(clicked()), this, SLOT(editMetaButtonClicked()));
400 connect(ui->buttonClearMeta, SIGNAL(clicked()), this, SLOT(clearMetaButtonClicked()));
401 connect(ui->writeMetaDataCheckBox, SIGNAL(clicked()), this, SLOT(metaTagsEnabledChanged()));
402 connect(ui->generatePlaylistCheckBox, SIGNAL(clicked()), this, SLOT(playlistEnabledChanged()));
404 //--------------------------------
405 //Setup "Compression" tab
406 //--------------------------------
408 m_encoderButtonGroup = new QButtonGroup(this);
409 m_encoderButtonGroup->addButton(ui->radioButtonEncoderMP3, SettingsModel::MP3Encoder);
410 m_encoderButtonGroup->addButton(ui->radioButtonEncoderVorbis, SettingsModel::VorbisEncoder);
411 m_encoderButtonGroup->addButton(ui->radioButtonEncoderAAC, SettingsModel::AACEncoder);
412 m_encoderButtonGroup->addButton(ui->radioButtonEncoderAC3, SettingsModel::AC3Encoder);
413 m_encoderButtonGroup->addButton(ui->radioButtonEncoderFLAC, SettingsModel::FLACEncoder);
414 m_encoderButtonGroup->addButton(ui->radioButtonEncoderAPE, SettingsModel::MACEncoder);
415 m_encoderButtonGroup->addButton(ui->radioButtonEncoderOpus, SettingsModel::OpusEncoder);
416 m_encoderButtonGroup->addButton(ui->radioButtonEncoderDCA, SettingsModel::DCAEncoder);
417 m_encoderButtonGroup->addButton(ui->radioButtonEncoderPCM, SettingsModel::PCMEncoder);
419 const int aacEncoder = EncoderRegistry::getAacEncoder();
420 ui->radioButtonEncoderAAC->setEnabled(aacEncoder > SettingsModel::AAC_ENCODER_NONE);
422 m_modeButtonGroup = new QButtonGroup(this);
423 m_modeButtonGroup->addButton(ui->radioButtonModeQuality, SettingsModel::VBRMode);
424 m_modeButtonGroup->addButton(ui->radioButtonModeAverageBitrate, SettingsModel::ABRMode);
425 m_modeButtonGroup->addButton(ui->radioButtonConstBitrate, SettingsModel::CBRMode);
427 ui->radioButtonEncoderMP3->setChecked(true);
428 foreach(QAbstractButton *currentButton, m_encoderButtonGroup->buttons())
430 if(currentButton->isEnabled() && (m_encoderButtonGroup->id(currentButton) == m_settings->compressionEncoder()))
432 currentButton->setChecked(true);
437 m_evenFilterCompressionTab = new CustomEventFilter();
438 ui->labelCompressionHelp->installEventFilter(m_evenFilterCompressionTab);
439 ui->labelResetEncoders ->installEventFilter(m_evenFilterCompressionTab);
441 connect(m_encoderButtonGroup, SIGNAL(buttonClicked(int)), this, SLOT(updateEncoder(int)));
442 connect(m_modeButtonGroup, SIGNAL(buttonClicked(int)), this, SLOT(updateRCMode(int)));
443 connect(m_evenFilterCompressionTab, SIGNAL(eventOccurred(QWidget*, QEvent*)), this, SLOT(compressionTabEventOccurred(QWidget*, QEvent*)));
444 connect(ui->sliderBitrate, SIGNAL(valueChanged(int)), this, SLOT(updateBitrate(int)));
446 updateEncoder(m_encoderButtonGroup->checkedId());
448 //--------------------------------
449 //Setup "Advanced Options" tab
450 //--------------------------------
452 ui->sliderLameAlgoQuality->setValue(m_settings->lameAlgoQuality());
453 if(m_settings->maximumInstances() > 0) ui->sliderMaxInstances->setValue(m_settings->maximumInstances());
455 ui->spinBoxBitrateManagementMin->setValue(m_settings->bitrateManagementMinRate());
456 ui->spinBoxBitrateManagementMax->setValue(m_settings->bitrateManagementMaxRate());
457 ui->spinBoxNormalizationFilter->setValue(static_cast<double>(m_settings->normalizationFilterMaxVolume()) / 100.0);
458 ui->spinBoxToneAdjustBass->setValue(static_cast<double>(m_settings->toneAdjustBass()) / 100.0);
459 ui->spinBoxToneAdjustTreble->setValue(static_cast<double>(m_settings->toneAdjustTreble()) / 100.0);
460 ui->spinBoxAftenSearchSize->setValue(m_settings->aftenExponentSearchSize());
461 ui->spinBoxOpusComplexity->setValue(m_settings->opusComplexity());
463 ui->comboBoxMP3ChannelMode->setCurrentIndex(m_settings->lameChannelMode());
464 ui->comboBoxSamplingRate->setCurrentIndex(m_settings->samplingRate());
465 ui->comboBoxAACProfile->setCurrentIndex(m_settings->aacEncProfile());
466 ui->comboBoxAftenCodingMode->setCurrentIndex(m_settings->aftenAudioCodingMode());
467 ui->comboBoxAftenDRCMode->setCurrentIndex(m_settings->aftenDynamicRangeCompression());
468 ui->comboBoxNormalizationMode->setCurrentIndex(m_settings->normalizationFilterEQMode());
469 ui->comboBoxOpusFramesize->setCurrentIndex(m_settings->opusFramesize());
471 SET_CHECKBOX_STATE(ui->checkBoxBitrateManagement, m_settings->bitrateManagementEnabled());
472 SET_CHECKBOX_STATE(ui->checkBoxNeroAAC2PassMode, m_settings->neroAACEnable2Pass());
473 SET_CHECKBOX_STATE(ui->checkBoxAftenFastAllocation, m_settings->aftenFastBitAllocation());
474 SET_CHECKBOX_STATE(ui->checkBoxNormalizationFilter, m_settings->normalizationFilterEnabled());
475 SET_CHECKBOX_STATE(ui->checkBoxAutoDetectInstances, (m_settings->maximumInstances() < 1));
476 SET_CHECKBOX_STATE(ui->checkBoxUseSystemTempFolder, !m_settings->customTempPathEnabled());
477 SET_CHECKBOX_STATE(ui->checkBoxRenameOutput, m_settings->renameOutputFilesEnabled());
478 SET_CHECKBOX_STATE(ui->checkBoxForceStereoDownmix, m_settings->forceStereoDownmix());
479 SET_CHECKBOX_STATE(ui->checkBoxOpusDisableResample, m_settings->opusDisableResample());
480 ui->checkBoxNeroAAC2PassMode->setEnabled(aacEncoder == SettingsModel::AAC_ENCODER_NERO);
482 ui->lineEditCustomParamLAME ->setText(EncoderRegistry::loadEncoderCustomParams(m_settings, SettingsModel::MP3Encoder));
483 ui->lineEditCustomParamOggEnc ->setText(EncoderRegistry::loadEncoderCustomParams(m_settings, SettingsModel::VorbisEncoder));
484 ui->lineEditCustomParamNeroAAC->setText(EncoderRegistry::loadEncoderCustomParams(m_settings, SettingsModel::AACEncoder));
485 ui->lineEditCustomParamFLAC ->setText(EncoderRegistry::loadEncoderCustomParams(m_settings, SettingsModel::FLACEncoder));
486 ui->lineEditCustomParamAften ->setText(EncoderRegistry::loadEncoderCustomParams(m_settings, SettingsModel::AC3Encoder));
487 ui->lineEditCustomParamOpus ->setText(EncoderRegistry::loadEncoderCustomParams(m_settings, SettingsModel::OpusEncoder));
488 ui->lineEditCustomTempFolder ->setText(QDir::toNativeSeparators(m_settings->customTempPath()));
489 ui->lineEditRenamePattern ->setText(m_settings->renameOutputFilesPattern());
491 m_evenFilterCustumParamsHelp = new CustomEventFilter();
492 ui->helpCustomParamLAME->installEventFilter(m_evenFilterCustumParamsHelp);
493 ui->helpCustomParamOggEnc->installEventFilter(m_evenFilterCustumParamsHelp);
494 ui->helpCustomParamNeroAAC->installEventFilter(m_evenFilterCustumParamsHelp);
495 ui->helpCustomParamFLAC->installEventFilter(m_evenFilterCustumParamsHelp);
496 ui->helpCustomParamAften->installEventFilter(m_evenFilterCustumParamsHelp);
497 ui->helpCustomParamOpus->installEventFilter(m_evenFilterCustumParamsHelp);
499 m_overwriteButtonGroup = new QButtonGroup(this);
500 m_overwriteButtonGroup->addButton(ui->radioButtonOverwriteModeKeepBoth, SettingsModel::Overwrite_KeepBoth);
501 m_overwriteButtonGroup->addButton(ui->radioButtonOverwriteModeSkipFile, SettingsModel::Overwrite_SkipFile);
502 m_overwriteButtonGroup->addButton(ui->radioButtonOverwriteModeReplaces, SettingsModel::Overwrite_Replaces);
504 ui->radioButtonOverwriteModeKeepBoth->setChecked(m_settings->overwriteMode() == SettingsModel::Overwrite_KeepBoth);
505 ui->radioButtonOverwriteModeSkipFile->setChecked(m_settings->overwriteMode() == SettingsModel::Overwrite_SkipFile);
506 ui->radioButtonOverwriteModeReplaces->setChecked(m_settings->overwriteMode() == SettingsModel::Overwrite_Replaces);
508 connect(ui->sliderLameAlgoQuality, SIGNAL(valueChanged(int)), this, SLOT(updateLameAlgoQuality(int)));
509 connect(ui->checkBoxBitrateManagement, SIGNAL(clicked(bool)), this, SLOT(bitrateManagementEnabledChanged(bool)));
510 connect(ui->spinBoxBitrateManagementMin, SIGNAL(valueChanged(int)), this, SLOT(bitrateManagementMinChanged(int)));
511 connect(ui->spinBoxBitrateManagementMax, SIGNAL(valueChanged(int)), this, SLOT(bitrateManagementMaxChanged(int)));
512 connect(ui->comboBoxMP3ChannelMode, SIGNAL(currentIndexChanged(int)), this, SLOT(channelModeChanged(int)));
513 connect(ui->comboBoxSamplingRate, SIGNAL(currentIndexChanged(int)), this, SLOT(samplingRateChanged(int)));
514 connect(ui->checkBoxNeroAAC2PassMode, SIGNAL(clicked(bool)), this, SLOT(neroAAC2PassChanged(bool)));
515 connect(ui->comboBoxAACProfile, SIGNAL(currentIndexChanged(int)), this, SLOT(neroAACProfileChanged(int)));
516 connect(ui->checkBoxNormalizationFilter, SIGNAL(clicked(bool)), this, SLOT(normalizationEnabledChanged(bool)));
517 connect(ui->comboBoxAftenCodingMode, SIGNAL(currentIndexChanged(int)), this, SLOT(aftenCodingModeChanged(int)));
518 connect(ui->comboBoxAftenDRCMode, SIGNAL(currentIndexChanged(int)), this, SLOT(aftenDRCModeChanged(int)));
519 connect(ui->spinBoxAftenSearchSize, SIGNAL(valueChanged(int)), this, SLOT(aftenSearchSizeChanged(int)));
520 connect(ui->checkBoxAftenFastAllocation, SIGNAL(clicked(bool)), this, SLOT(aftenFastAllocationChanged(bool)));
521 connect(ui->spinBoxNormalizationFilter, SIGNAL(valueChanged(double)), this, SLOT(normalizationMaxVolumeChanged(double)));
522 connect(ui->comboBoxNormalizationMode, SIGNAL(currentIndexChanged(int)), this, SLOT(normalizationModeChanged(int)));
523 connect(ui->spinBoxToneAdjustBass, SIGNAL(valueChanged(double)), this, SLOT(toneAdjustBassChanged(double)));
524 connect(ui->spinBoxToneAdjustTreble, SIGNAL(valueChanged(double)), this, SLOT(toneAdjustTrebleChanged(double)));
525 connect(ui->buttonToneAdjustReset, SIGNAL(clicked()), this, SLOT(toneAdjustTrebleReset()));
526 connect(ui->lineEditCustomParamLAME, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
527 connect(ui->lineEditCustomParamOggEnc, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
528 connect(ui->lineEditCustomParamNeroAAC, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
529 connect(ui->lineEditCustomParamFLAC, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
530 connect(ui->lineEditCustomParamAften, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
531 connect(ui->lineEditCustomParamOpus, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
532 connect(ui->sliderMaxInstances, SIGNAL(valueChanged(int)), this, SLOT(updateMaximumInstances(int)));
533 connect(ui->checkBoxAutoDetectInstances, SIGNAL(clicked(bool)), this, SLOT(autoDetectInstancesChanged(bool)));
534 connect(ui->buttonBrowseCustomTempFolder, SIGNAL(clicked()), this, SLOT(browseCustomTempFolderButtonClicked()));
535 connect(ui->lineEditCustomTempFolder, SIGNAL(textChanged(QString)), this, SLOT(customTempFolderChanged(QString)));
536 connect(ui->checkBoxUseSystemTempFolder, SIGNAL(clicked(bool)), this, SLOT(useCustomTempFolderChanged(bool)));
537 connect(ui->buttonResetAdvancedOptions, SIGNAL(clicked()), this, SLOT(resetAdvancedOptionsButtonClicked()));
538 connect(ui->checkBoxRenameOutput, SIGNAL(clicked(bool)), this, SLOT(renameOutputEnabledChanged(bool)));
539 connect(ui->lineEditRenamePattern, SIGNAL(editingFinished()), this, SLOT(renameOutputPatternChanged()));
540 connect(ui->lineEditRenamePattern, SIGNAL(textChanged(QString)), this, SLOT(renameOutputPatternChanged(QString)));
541 connect(ui->labelShowRenameMacros, SIGNAL(linkActivated(QString)), this, SLOT(showRenameMacros(QString)));
542 connect(ui->checkBoxForceStereoDownmix, SIGNAL(clicked(bool)), this, SLOT(forceStereoDownmixEnabledChanged(bool)));
543 connect(ui->comboBoxOpusFramesize, SIGNAL(currentIndexChanged(int)), this, SLOT(opusSettingsChanged()));
544 connect(ui->spinBoxOpusComplexity, SIGNAL(valueChanged(int)), this, SLOT(opusSettingsChanged()));
545 connect(ui->checkBoxOpusDisableResample, SIGNAL(clicked(bool)), SLOT(opusSettingsChanged()));
546 connect(m_overwriteButtonGroup, SIGNAL(buttonClicked(int)), this, SLOT(overwriteModeChanged(int)));
547 connect(m_evenFilterCustumParamsHelp, SIGNAL(eventOccurred(QWidget*, QEvent*)), this, SLOT(customParamsHelpRequested(QWidget*, QEvent*)));
549 //--------------------------------
550 // Force initial GUI update
551 //--------------------------------
553 updateLameAlgoQuality(ui->sliderLameAlgoQuality->value());
554 updateMaximumInstances(ui->sliderMaxInstances->value());
555 toneAdjustTrebleChanged(ui->spinBoxToneAdjustTreble->value());
556 toneAdjustBassChanged(ui->spinBoxToneAdjustBass->value());
557 customParamsChanged();
559 //--------------------------------
560 // Initialize actions
561 //--------------------------------
563 //Activate file menu actions
564 ui->actionOpenFolder->setData(QVariant::fromValue<bool>(false));
565 ui->actionOpenFolderRecursively->setData(QVariant::fromValue<bool>(true));
566 connect(ui->actionOpenFolder, SIGNAL(triggered()), this, SLOT(openFolderActionActivated()));
567 connect(ui->actionOpenFolderRecursively, SIGNAL(triggered()), this, SLOT(openFolderActionActivated()));
569 //Activate view menu actions
570 m_tabActionGroup = new QActionGroup(this);
571 m_tabActionGroup->addAction(ui->actionSourceFiles);
572 m_tabActionGroup->addAction(ui->actionOutputDirectory);
573 m_tabActionGroup->addAction(ui->actionCompression);
574 m_tabActionGroup->addAction(ui->actionMetaData);
575 m_tabActionGroup->addAction(ui->actionAdvancedOptions);
576 ui->actionSourceFiles->setData(0);
577 ui->actionOutputDirectory->setData(1);
578 ui->actionMetaData->setData(2);
579 ui->actionCompression->setData(3);
580 ui->actionAdvancedOptions->setData(4);
581 ui->actionSourceFiles->setChecked(true);
582 connect(m_tabActionGroup, SIGNAL(triggered(QAction*)), this, SLOT(tabActionActivated(QAction*)));
584 //Activate style menu actions
585 m_styleActionGroup = new QActionGroup(this);
586 m_styleActionGroup->addAction(ui->actionStylePlastique);
587 m_styleActionGroup->addAction(ui->actionStyleCleanlooks);
588 m_styleActionGroup->addAction(ui->actionStyleWindowsVista);
589 m_styleActionGroup->addAction(ui->actionStyleWindowsXP);
590 m_styleActionGroup->addAction(ui->actionStyleWindowsClassic);
591 ui->actionStylePlastique->setData(0);
592 ui->actionStyleCleanlooks->setData(1);
593 ui->actionStyleWindowsVista->setData(2);
594 ui->actionStyleWindowsXP->setData(3);
595 ui->actionStyleWindowsClassic->setData(4);
596 ui->actionStylePlastique->setChecked(true);
597 ui->actionStyleWindowsXP->setEnabled((QSysInfo::windowsVersion() & QSysInfo::WV_NT_based) >= QSysInfo::WV_XP && lamexp_themes_enabled());
598 ui->actionStyleWindowsVista->setEnabled((QSysInfo::windowsVersion() & QSysInfo::WV_NT_based) >= QSysInfo::WV_VISTA && lamexp_themes_enabled());
599 connect(m_styleActionGroup, SIGNAL(triggered(QAction*)), this, SLOT(styleActionActivated(QAction*)));
600 styleActionActivated(NULL);
602 //Populate the language menu
603 m_languageActionGroup = new QActionGroup(this);
604 QStringList translations = lamexp_query_translations();
605 while(!translations.isEmpty())
607 QString langId = translations.takeFirst();
608 QAction *currentLanguage = new QAction(this);
609 currentLanguage->setData(langId);
610 currentLanguage->setText(lamexp_translation_name(langId));
611 currentLanguage->setIcon(QIcon(QString(":/flags/%1.png").arg(langId)));
612 currentLanguage->setCheckable(true);
613 currentLanguage->setChecked(false);
614 m_languageActionGroup->addAction(currentLanguage);
615 ui->menuLanguage->insertAction(ui->actionLoadTranslationFromFile, currentLanguage);
617 ui->menuLanguage->insertSeparator(ui->actionLoadTranslationFromFile);
618 connect(ui->actionLoadTranslationFromFile, SIGNAL(triggered(bool)), this, SLOT(languageFromFileActionActivated(bool)));
619 connect(m_languageActionGroup, SIGNAL(triggered(QAction*)), this, SLOT(languageActionActivated(QAction*)));
620 ui->actionLoadTranslationFromFile->setChecked(false);
622 //Activate tools menu actions
623 ui->actionDisableUpdateReminder->setChecked(!m_settings->autoUpdateEnabled());
624 ui->actionDisableSounds->setChecked(!m_settings->soundsEnabled());
625 ui->actionDisableNeroAacNotifications->setChecked(!m_settings->neroAacNotificationsEnabled());
626 ui->actionDisableSlowStartupNotifications->setChecked(!m_settings->antivirNotificationsEnabled());
627 ui->actionDisableShellIntegration->setChecked(!m_settings->shellIntegrationEnabled());
628 ui->actionDisableShellIntegration->setDisabled(lamexp_portable_mode() && ui->actionDisableShellIntegration->isChecked());
629 ui->actionCheckForBetaUpdates->setChecked(m_settings->autoUpdateCheckBeta() || lamexp_version_demo());
630 ui->actionCheckForBetaUpdates->setEnabled(!lamexp_version_demo());
631 ui->actionHibernateComputer->setChecked(m_settings->hibernateComputer());
632 ui->actionHibernateComputer->setEnabled(MUtils::OS::is_hibernation_supported());
633 connect(ui->actionDisableUpdateReminder, SIGNAL(triggered(bool)), this, SLOT(disableUpdateReminderActionTriggered(bool)));
634 connect(ui->actionDisableSounds, SIGNAL(triggered(bool)), this, SLOT(disableSoundsActionTriggered(bool)));
635 connect(ui->actionDisableNeroAacNotifications, SIGNAL(triggered(bool)), this, SLOT(disableNeroAacNotificationsActionTriggered(bool)));
636 connect(ui->actionDisableSlowStartupNotifications, SIGNAL(triggered(bool)), this, SLOT(disableSlowStartupNotificationsActionTriggered(bool)));
637 connect(ui->actionDisableShellIntegration, SIGNAL(triggered(bool)), this, SLOT(disableShellIntegrationActionTriggered(bool)));
638 connect(ui->actionShowDropBoxWidget, SIGNAL(triggered(bool)), this, SLOT(showDropBoxWidgetActionTriggered(bool)));
639 connect(ui->actionHibernateComputer, SIGNAL(triggered(bool)), this, SLOT(hibernateComputerActionTriggered(bool)));
640 connect(ui->actionCheckForBetaUpdates, SIGNAL(triggered(bool)), this, SLOT(checkForBetaUpdatesActionTriggered(bool)));
641 connect(ui->actionImportCueSheet, SIGNAL(triggered(bool)), this, SLOT(importCueSheetActionTriggered(bool)));
643 //Activate help menu actions
644 ui->actionVisitHomepage ->setData(QString::fromLatin1(lamexp_website_url()));
645 ui->actionVisitSupport ->setData(QString::fromLatin1(lamexp_support_url()));
646 ui->actionVisitMuldersSite ->setData(QString::fromLatin1(lamexp_mulders_url()));
647 ui->actionVisitTracker ->setData(QString::fromLatin1(lamexp_tracker_url()));
648 ui->actionVisitHAK ->setData(QString::fromLatin1(g_hydrogen_audio_url));
649 ui->actionDocumentFAQ ->setData(QString("%1/FAQ.html").arg(QApplication::applicationDirPath()));
650 ui->actionDocumentChangelog->setData(QString("%1/Changelog.html").arg(QApplication::applicationDirPath()));
651 ui->actionDocumentTranslate->setData(QString("%1/Translate.html").arg(QApplication::applicationDirPath()));
652 connect(ui->actionCheckUpdates, SIGNAL(triggered()), this, SLOT(checkUpdatesActionActivated()));
653 connect(ui->actionVisitSupport, SIGNAL(triggered()), this, SLOT(visitHomepageActionActivated()));
654 connect(ui->actionVisitTracker, SIGNAL(triggered()), this, SLOT(visitHomepageActionActivated()));
655 connect(ui->actionVisitHomepage, SIGNAL(triggered()), this, SLOT(visitHomepageActionActivated()));
656 connect(ui->actionVisitMuldersSite, SIGNAL(triggered()), this, SLOT(visitHomepageActionActivated()));
657 connect(ui->actionVisitHAK, SIGNAL(triggered()), this, SLOT(visitHomepageActionActivated()));
658 connect(ui->actionDocumentFAQ, SIGNAL(triggered()), this, SLOT(documentActionActivated()));
659 connect(ui->actionDocumentChangelog, SIGNAL(triggered()), this, SLOT(documentActionActivated()));
660 connect(ui->actionDocumentTranslate, SIGNAL(triggered()), this, SLOT(documentActionActivated()));
662 //--------------------------------
663 // Prepare to show window
664 //--------------------------------
666 //Center window in screen
667 QRect desktopRect = QApplication::desktop()->screenGeometry();
668 QRect thisRect = this->geometry();
669 move((desktopRect.width() - thisRect.width()) / 2, (desktopRect.height() - thisRect.height()) / 2);
670 setMinimumSize(thisRect.width(), thisRect.height());
672 //Create DropBox widget
673 m_dropBox = new DropBox(this, m_fileListModel, m_settings);
674 connect(m_fileListModel, SIGNAL(modelReset()), m_dropBox, SLOT(modelChanged()));
675 connect(m_fileListModel, SIGNAL(rowsInserted(QModelIndex,int,int)), m_dropBox, SLOT(modelChanged()));
676 connect(m_fileListModel, SIGNAL(rowsRemoved(QModelIndex,int,int)), m_dropBox, SLOT(modelChanged()));
677 connect(m_fileListModel, SIGNAL(rowAppended()), m_dropBox, SLOT(modelChanged()));
679 //Create message handler thread
680 m_messageHandler = new MessageHandlerThread();
681 connect(m_messageHandler, SIGNAL(otherInstanceDetected()), this, SLOT(notifyOtherInstance()), Qt::QueuedConnection);
682 connect(m_messageHandler, SIGNAL(fileReceived(QString)), this, SLOT(addFileDelayed(QString)), Qt::QueuedConnection);
683 connect(m_messageHandler, SIGNAL(folderReceived(QString, bool)), this, SLOT(addFolderDelayed(QString, bool)), Qt::QueuedConnection);
684 connect(m_messageHandler, SIGNAL(killSignalReceived()), this, SLOT(close()), Qt::QueuedConnection);
685 m_messageHandler->start();
687 //Init delayed file handling
688 m_delayedFileList = new QStringList();
689 m_delayedFileTimer = new QTimer();
690 m_delayedFileTimer->setSingleShot(true);
691 m_delayedFileTimer->setInterval(5000);
692 connect(m_delayedFileTimer, SIGNAL(timeout()), this, SLOT(handleDelayedFiles()));
695 initializeTranslation();
697 //Re-translate (make sure we translate once)
698 QEvent languageChangeEvent(QEvent::LanguageChange);
699 changeEvent(&languageChangeEvent);
702 m_droppedFileList = new QList<QUrl>();
703 this->setAcceptDrops(true);
706 ////////////////////////////////////////////////////////////
708 ////////////////////////////////////////////////////////////
710 MainWindow::~MainWindow(void)
712 //Stop message handler thread
713 if(m_messageHandler && m_messageHandler->isRunning())
715 m_messageHandler->stop();
716 if(!m_messageHandler->wait(2500))
718 m_messageHandler->terminate();
719 m_messageHandler->wait();
724 SET_MODEL(ui->sourceFileView, NULL);
725 SET_MODEL(ui->outputFolderView, NULL);
726 SET_MODEL(ui->metaDataView, NULL);
729 MUTILS_DELETE(m_tabActionGroup);
730 MUTILS_DELETE(m_styleActionGroup);
731 MUTILS_DELETE(m_languageActionGroup);
732 MUTILS_DELETE(m_banner);
733 MUTILS_DELETE(m_fileSystemModel);
734 MUTILS_DELETE(m_messageHandler);
735 MUTILS_DELETE(m_droppedFileList);
736 MUTILS_DELETE(m_delayedFileList);
737 MUTILS_DELETE(m_delayedFileTimer);
738 MUTILS_DELETE(m_metaInfoModel);
739 MUTILS_DELETE(m_encoderButtonGroup);
740 MUTILS_DELETE(m_modeButtonGroup);
741 MUTILS_DELETE(m_overwriteButtonGroup);
742 MUTILS_DELETE(m_sourceFilesContextMenu);
743 MUTILS_DELETE(m_outputFolderFavoritesMenu);
744 MUTILS_DELETE(m_outputFolderContextMenu);
745 MUTILS_DELETE(m_dropBox);
746 MUTILS_DELETE(m_evenFilterCornerWidget);
747 MUTILS_DELETE(m_evenFilterCustumParamsHelp);
748 MUTILS_DELETE(m_evenFilterOutputFolderMouse);
749 MUTILS_DELETE(m_evenFilterOutputFolderView);
750 MUTILS_DELETE(m_evenFilterCompressionTab);
752 //Un-initialize the dialog
756 ////////////////////////////////////////////////////////////
758 ////////////////////////////////////////////////////////////
761 * Add file to source list
763 void MainWindow::addFiles(const QStringList &files)
770 WITH_BLOCKED_SIGNALS(ui->tabWidget, setCurrentIndex, 0);
771 tabPageChanged(ui->tabWidget->currentIndex(), true);
774 FileAnalyzer *analyzer = new FileAnalyzer(files);
776 connect(analyzer, SIGNAL(fileSelected(QString)), m_banner, SLOT(setText(QString)), Qt::QueuedConnection);
777 connect(analyzer, SIGNAL(progressValChanged(unsigned int)), m_banner, SLOT(setProgressVal(unsigned int)), Qt::QueuedConnection);
778 connect(analyzer, SIGNAL(progressMaxChanged(unsigned int)), m_banner, SLOT(setProgressMax(unsigned int)), Qt::QueuedConnection);
779 connect(analyzer, SIGNAL(fileAnalyzed(AudioFileModel)), m_fileListModel, SLOT(addFile(AudioFileModel)), Qt::QueuedConnection);
780 connect(m_banner, SIGNAL(userAbort()), analyzer, SLOT(abortProcess()), Qt::DirectConnection);
784 m_fileListModel->setBlockUpdates(true);
785 QTime startTime = QTime::currentTime();
786 m_banner->show(tr("Adding file(s), please wait..."), analyzer);
790 /* ignore any exceptions that may occur */
793 m_fileListModel->setBlockUpdates(false);
794 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
795 ui->sourceFileView->update();
796 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
797 ui->sourceFileView->scrollToBottom();
798 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
800 if(analyzer->filesDenied())
802 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."))));
804 if(analyzer->filesDummyCDDA())
806 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>"))));
808 if(analyzer->filesCueSheet())
810 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."))));
812 if(analyzer->filesRejected())
814 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."))));
817 MUTILS_DELETE(analyzer);
822 * Add folder to source list
824 void MainWindow::addFolder(const QString &path, bool recursive, bool delayed)
826 QFileInfoList folderInfoList;
827 folderInfoList << QFileInfo(path);
828 QStringList fileList;
830 SHOW_BANNER(tr("Scanning folder(s) for files, please wait..."));
832 QApplication::processEvents();
833 lamexp_check_escape_state();
835 while(!folderInfoList.isEmpty())
837 if(lamexp_check_escape_state())
839 lamexp_beep(lamexp_beep_error);
840 qWarning("Operation cancelled by user!");
845 QDir currentDir(folderInfoList.takeFirst().canonicalFilePath());
846 QFileInfoList fileInfoList = currentDir.entryInfoList(QDir::Files | QDir::NoSymLinks);
848 while(!fileInfoList.isEmpty())
850 fileList << fileInfoList.takeFirst().canonicalFilePath();
853 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
857 folderInfoList.append(currentDir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks));
858 QApplication::processEvents();
863 QApplication::processEvents();
865 if(!fileList.isEmpty())
869 addFilesDelayed(fileList);
881 bool MainWindow::checkForUpdates(void)
883 bool bReadyToInstall = false;
885 UpdateDialog *updateDialog = new UpdateDialog(m_settings, this);
886 updateDialog->exec();
888 if(updateDialog->getSuccess())
890 SHOW_CORNER_WIDGET(false);
891 m_settings->autoUpdateLastCheck(QDate::currentDate().toString(Qt::ISODate));
892 bReadyToInstall = updateDialog->updateReadyToInstall();
895 MUTILS_DELETE(updateDialog);
896 return bReadyToInstall;
900 * Refresh list of favorites
902 void MainWindow::refreshFavorites(void)
904 QList<QAction*> folderList = m_outputFolderFavoritesMenu->actions();
905 QStringList favorites = m_settings->favoriteOutputFolders().split("|", QString::SkipEmptyParts);
906 while(favorites.count() > 6) favorites.removeFirst();
908 while(!folderList.isEmpty())
910 QAction *currentItem = folderList.takeFirst();
911 if(currentItem->isSeparator()) break;
912 m_outputFolderFavoritesMenu->removeAction(currentItem);
913 MUTILS_DELETE(currentItem);
916 QAction *lastItem = m_outputFolderFavoritesMenu->actions().first();
918 while(!favorites.isEmpty())
920 QString path = favorites.takeLast();
921 if(QDir(path).exists())
923 QAction *action = new QAction(QIcon(":/icons/folder_go.png"), QDir::toNativeSeparators(path), this);
924 action->setData(path);
925 m_outputFolderFavoritesMenu->insertAction(lastItem, action);
926 connect(action, SIGNAL(triggered(bool)), this, SLOT(gotoFavoriteFolder()));
933 * Initilaize translation
935 void MainWindow::initializeTranslation(void)
937 bool translationLoaded = false;
939 //Try to load "external" translation file
940 if(!m_settings->currentLanguageFile().isEmpty())
942 const QString qmFilePath = QFileInfo(m_settings->currentLanguageFile()).canonicalFilePath();
943 if((!qmFilePath.isEmpty()) && QFileInfo(qmFilePath).exists() && QFileInfo(qmFilePath).isFile() && (QFileInfo(qmFilePath).suffix().compare("qm", Qt::CaseInsensitive) == 0))
945 if(lamexp_install_translator_from_file(qmFilePath))
947 QList<QAction*> actions = m_languageActionGroup->actions();
948 while(!actions.isEmpty()) actions.takeFirst()->setChecked(false);
949 ui->actionLoadTranslationFromFile->setChecked(true);
950 translationLoaded = true;
955 //Try to load "built-in" translation file
956 if(!translationLoaded)
958 QList<QAction*> languageActions = m_languageActionGroup->actions();
959 while(!languageActions.isEmpty())
961 QAction *currentLanguage = languageActions.takeFirst();
962 if(currentLanguage->data().toString().compare(m_settings->currentLanguage(), Qt::CaseInsensitive) == 0)
964 currentLanguage->setChecked(true);
965 languageActionActivated(currentLanguage);
966 translationLoaded = true;
971 //Fallback to default translation
972 if(!translationLoaded)
974 QList<QAction*> languageActions = m_languageActionGroup->actions();
975 while(!languageActions.isEmpty())
977 QAction *currentLanguage = languageActions.takeFirst();
978 if(currentLanguage->data().toString().compare(LAMEXP_DEFAULT_LANGID, Qt::CaseInsensitive) == 0)
980 currentLanguage->setChecked(true);
981 languageActionActivated(currentLanguage);
982 translationLoaded = true;
987 //Make sure we loaded some translation
988 if(!translationLoaded)
990 qFatal("Failed to load any translation, this is NOT supposed to happen!");
994 ////////////////////////////////////////////////////////////
996 ////////////////////////////////////////////////////////////
999 * Window is about to be shown
1001 void MainWindow::showEvent(QShowEvent *event)
1005 sourceModelChanged();
1007 if(!event->spontaneous())
1009 WITH_BLOCKED_SIGNALS(ui->tabWidget, setCurrentIndex, 0);
1010 tabPageChanged(ui->tabWidget->currentIndex(), true);
1013 if(m_firstTimeShown)
1015 m_firstTimeShown = false;
1016 QTimer::singleShot(0, this, SLOT(windowShown()));
1020 if(m_settings->dropBoxWidgetEnabled())
1022 m_dropBox->setVisible(true);
1028 * Re-translate the UI
1030 void MainWindow::changeEvent(QEvent *e)
1032 QMainWindow::changeEvent(e);
1033 if(e->type() != QEvent::LanguageChange)
1038 int comboBoxIndex[8];
1040 //Backup combobox indices, as retranslateUi() resets
1041 comboBoxIndex[0] = ui->comboBoxMP3ChannelMode->currentIndex();
1042 comboBoxIndex[1] = ui->comboBoxSamplingRate->currentIndex();
1043 comboBoxIndex[2] = ui->comboBoxAACProfile->currentIndex();
1044 comboBoxIndex[3] = ui->comboBoxAftenCodingMode->currentIndex();
1045 comboBoxIndex[4] = ui->comboBoxAftenDRCMode->currentIndex();
1046 comboBoxIndex[5] = ui->comboBoxNormalizationMode->currentIndex();
1047 comboBoxIndex[6] = 0; //comboBoxOpusOptimize->currentIndex();
1048 comboBoxIndex[7] = ui->comboBoxOpusFramesize->currentIndex();
1050 //Re-translate from UIC
1051 ui->retranslateUi(this);
1053 //Restore combobox indices
1054 ui->comboBoxMP3ChannelMode->setCurrentIndex(comboBoxIndex[0]);
1055 ui->comboBoxSamplingRate->setCurrentIndex(comboBoxIndex[1]);
1056 ui->comboBoxAACProfile->setCurrentIndex(comboBoxIndex[2]);
1057 ui->comboBoxAftenCodingMode->setCurrentIndex(comboBoxIndex[3]);
1058 ui->comboBoxAftenDRCMode->setCurrentIndex(comboBoxIndex[4]);
1059 ui->comboBoxNormalizationMode->setCurrentIndex(comboBoxIndex[5]);
1060 //comboBoxOpusOptimize->setCurrentIndex(comboBoxIndex[6]);
1061 ui->comboBoxOpusFramesize->setCurrentIndex(comboBoxIndex[7]);
1063 //Update the window title
1066 setWindowTitle(QString("%1 [!!! DEBUG BUILD !!!]").arg(windowTitle()));
1068 else if(lamexp_version_demo())
1070 setWindowTitle(QString("%1 [%2]").arg(windowTitle(), tr("DEMO VERSION")));
1073 //Manually re-translate widgets that UIC doesn't handle
1074 m_outputFolderNoteBox->setText(tr("Initializing directory outline, please be patient..."));
1075 m_dropNoteLabel->setText(QString("<br><img src=\":/images/DropZone.png\"><br><br>%1").arg(tr("You can drop in audio files here!")));
1076 if(QLabel *cornerWidget = dynamic_cast<QLabel*>(ui->menubar->cornerWidget()))
1078 cornerWidget->setText(QString("<nobr><img src=\":/icons/exclamation_small.png\"> <b style=\"color:darkred\">%1</b> </nobr>").arg(tr("Check for Updates")));
1080 m_showDetailsContextAction->setText(tr("Show Details"));
1081 m_previewContextAction->setText(tr("Open File in External Application"));
1082 m_findFileContextAction->setText(tr("Browse File Location"));
1083 m_showFolderContextAction->setText(tr("Browse Selected Folder"));
1084 m_refreshFolderContextAction->setText(tr("Refresh Directory Outline"));
1085 m_goUpFolderContextAction->setText(tr("Go To Parent Directory"));
1086 m_addFavoriteFolderAction->setText(tr("Bookmark Current Output Folder"));
1087 m_exportCsvContextAction->setText(tr("Export Meta Tags to CSV File"));
1088 m_importCsvContextAction->setText(tr("Import Meta Tags from CSV File"));
1091 m_metaInfoModel->clearData();
1092 m_metaInfoModel->setData(m_metaInfoModel->index(4, 1), m_settings->metaInfoPosition());
1093 updateEncoder(m_settings->compressionEncoder());
1094 updateLameAlgoQuality(ui->sliderLameAlgoQuality->value());
1095 updateMaximumInstances(ui->sliderMaxInstances->value());
1096 renameOutputPatternChanged(ui->lineEditRenamePattern->text(), true);
1098 //Re-install shell integration
1099 if(m_settings->shellIntegrationEnabled())
1101 ShellIntegration::install();
1104 //Translate system menu
1105 lamexp_update_sysmenu(this, IDM_ABOUTBOX, ui->buttonAbout->text());
1107 //Force resize event
1108 QApplication::postEvent(this, new QResizeEvent(this->size(), QSize()));
1109 for(QObjectList::ConstIterator iter = this->children().constBegin(); iter != this->children().constEnd(); iter++)
1111 if(QWidget *child = dynamic_cast<QWidget*>(*iter))
1113 QApplication::postEvent(child, new QResizeEvent(child->size(), QSize()));
1117 //Force tabe page change
1118 tabPageChanged(ui->tabWidget->currentIndex(), true);
1122 * File dragged over window
1124 void MainWindow::dragEnterEvent(QDragEnterEvent *event)
1126 QStringList formats = event->mimeData()->formats();
1128 if(formats.contains("application/x-qt-windows-mime;value=\"FileNameW\"", Qt::CaseInsensitive) && formats.contains("text/uri-list", Qt::CaseInsensitive))
1130 event->acceptProposedAction();
1135 * File dropped onto window
1137 void MainWindow::dropEvent(QDropEvent *event)
1139 m_droppedFileList->clear();
1140 (*m_droppedFileList) << event->mimeData()->urls();
1141 if(!m_droppedFileList->isEmpty())
1143 PLAY_SOUND_OPTIONAL("drop", true);
1144 QTimer::singleShot(0, this, SLOT(handleDroppedFiles()));
1149 * Window tries to close
1151 void MainWindow::closeEvent(QCloseEvent *event)
1153 if(BANNER_VISIBLE || m_delayedFileTimer->isActive())
1155 lamexp_beep(lamexp_beep_warning);
1166 * Window was resized
1168 void MainWindow::resizeEvent(QResizeEvent *event)
1170 if(event) QMainWindow::resizeEvent(event);
1172 if(QWidget *port = ui->sourceFileView->viewport())
1174 m_dropNoteLabel->setGeometry(port->geometry());
1177 if(QWidget *port = ui->outputFolderView->viewport())
1179 m_outputFolderNoteBox->setGeometry(16, (port->height() - 64) / 2, port->width() - 32, 64);
1184 * Key press event filter
1186 void MainWindow::keyPressEvent(QKeyEvent *e)
1188 if(e->key() == Qt::Key_Delete)
1190 if(ui->sourceFileView->isVisible())
1192 QTimer::singleShot(0, this, SLOT(removeFileButtonClicked()));
1197 if(e->modifiers().testFlag(Qt::ControlModifier) && (e->key() == Qt::Key_F5))
1199 initializeTranslation();
1200 lamexp_beep(lamexp_beep_info);
1204 if(e->key() == Qt::Key_F5)
1206 if(ui->outputFolderView->isVisible())
1208 QTimer::singleShot(0, this, SLOT(refreshFolderContextActionTriggered()));
1213 QMainWindow::keyPressEvent(e);
1219 bool MainWindow::eventFilter(QObject *obj, QEvent *event)
1221 if(obj == m_fileSystemModel)
1223 if(QApplication::overrideCursor() == NULL)
1225 QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
1226 QTimer::singleShot(250, this, SLOT(restoreCursor()));
1230 return QMainWindow::eventFilter(obj, event);
1233 bool MainWindow::event(QEvent *e)
1237 case MUtils::GUI::USER_EVENT_QUERYENDSESSION:
1238 qWarning("System is shutting down, main window prepares to close...");
1239 if(BANNER_VISIBLE) m_banner->close();
1240 if(m_delayedFileTimer->isActive()) m_delayedFileTimer->stop();
1242 case MUtils::GUI::USER_EVENT_ENDSESSION:
1243 qWarning("System is shutting down, main window will close now...");
1248 QApplication::processEvents(QEventLoop::WaitForMoreEvents & QEventLoop::ExcludeUserInputEvents);
1251 m_fileListModel->clearFiles();
1253 case QEvent::MouseButtonPress:
1254 if(ui->outputFolderEdit->isVisible())
1256 QTimer::singleShot(0, this, SLOT(outputFolderEditFinished()));
1259 return QMainWindow::event(e);
1263 bool MainWindow::winEvent(MSG *message, long *result)
1265 if(lamexp_check_sysmenu_msg(message, IDM_ABOUTBOX))
1267 QTimer::singleShot(0, ui->buttonAbout, SLOT(click()));
1271 return WinSevenTaskbar::handleWinEvent(message, result);
1274 ////////////////////////////////////////////////////////////
1276 ////////////////////////////////////////////////////////////
1278 // =========================================================
1279 // Show window slots
1280 // =========================================================
1285 void MainWindow::windowShown(void)
1287 const QStringList &arguments = MUtils::OS::arguments(); //QApplication::arguments();
1289 //Force resize event
1293 bool firstRun = false;
1294 for(int i = 0; i < arguments.count(); i++)
1296 /*QMessageBox::information(this, QString::number(i), arguments[i]);*/
1297 if(!arguments[i].compare("--first-run", Qt::CaseInsensitive)) firstRun = true;
1301 if((m_settings->licenseAccepted() <= 0) || firstRun)
1303 int iAccepted = m_settings->licenseAccepted();
1305 if((iAccepted == 0) || firstRun)
1307 AboutDialog *about = new AboutDialog(m_settings, this, true);
1308 iAccepted = about->exec();
1309 if(iAccepted <= 0) iAccepted = -2;
1310 MUTILS_DELETE(about);
1315 m_settings->licenseAccepted(++iAccepted);
1316 m_settings->syncNow();
1317 QApplication::processEvents();
1318 lamexp_play_sound("whammy", false);
1319 QMessageBox::critical(this, tr("License Declined"), tr("You have declined the license. Consequently the application will exit now!"), tr("Goodbye!"));
1320 QFileInfo uninstallerInfo = QFileInfo(QString("%1/Uninstall.exe").arg(QApplication::applicationDirPath()));
1321 if(uninstallerInfo.exists())
1323 QString uninstallerDir = uninstallerInfo.canonicalPath();
1324 QString uninstallerPath = uninstallerInfo.canonicalFilePath();
1325 for(int i = 0; i < 3; i++)
1327 if(MUtils::OS::shell_open(this, QDir::toNativeSeparators(uninstallerPath), "/Force", QDir::toNativeSeparators(uninstallerDir))) break;
1330 QApplication::quit();
1334 lamexp_play_sound("woohoo", false);
1335 m_settings->licenseAccepted(1);
1336 m_settings->syncNow();
1337 if(lamexp_version_demo()) showAnnounceBox();
1340 //Check for expiration
1341 if(lamexp_version_demo())
1343 if(MUtils::OS::current_date() >= lamexp_version_expires())
1345 qWarning("Binary has expired !!!");
1346 lamexp_play_sound("whammy", false);
1347 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)
1351 QApplication::quit();
1356 //Slow startup indicator
1357 if(m_settings->slowStartup() && m_settings->antivirNotificationsEnabled())
1360 message += NOBR(tr("It seems that a bogus anti-virus software is slowing down the startup of LameXP.")).append("<br>");
1361 message += NOBR(tr("Please refer to the %1 document for details and solutions!")).arg("<a href=\"http://lamexp.sourceforge.net/doc/FAQ.html#df406578\">F.A.Q.</a>").append("<br>");
1362 if(QMessageBox::warning(this, tr("Slow Startup"), message, tr("Discard"), tr("Don't Show Again")) == 1)
1364 m_settings->antivirNotificationsEnabled(false);
1365 ui->actionDisableSlowStartupNotifications->setChecked(!m_settings->antivirNotificationsEnabled());
1370 if(MUtils::OS::current_date() >= MUtils::Version::app_build_date().addYears(1))
1372 qWarning("Binary is more than a year old, time to update!");
1373 SHOW_CORNER_WIDGET(true);
1374 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"));
1378 if(checkForUpdates())
1380 QApplication::quit();
1385 QApplication::quit();
1388 QEventLoop loop; QTimer::singleShot(7000, &loop, SLOT(quit()));
1389 lamexp_play_sound("waiting", true);
1390 SHOW_BANNER_ARG(tr("Skipping update check this time, please be patient..."), &loop);
1396 QDate lastUpdateCheck = QDate::fromString(m_settings->autoUpdateLastCheck(), Qt::ISODate);
1397 if((!firstRun) && ((!lastUpdateCheck.isValid()) || (MUtils::OS::current_date() >= lastUpdateCheck.addDays(14))))
1399 SHOW_CORNER_WIDGET(true);
1400 if(m_settings->autoUpdateEnabled())
1402 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)
1404 if(checkForUpdates())
1406 QApplication::quit();
1414 //Check for AAC support
1415 const int aacEncoder = EncoderRegistry::getAacEncoder();
1416 if(aacEncoder == SettingsModel::AAC_ENCODER_NERO)
1418 if(m_settings->neroAacNotificationsEnabled())
1420 if(lamexp_tool_version("neroAacEnc.exe") < lamexp_toolver_neroaac())
1422 QString messageText;
1423 messageText += NOBR(tr("LameXP detected that your version of the Nero AAC encoder is outdated!")).append("<br>");
1424 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_tool_version("neroAacEnc.exe"), tr("n/a")))).append("<br><br>");
1425 messageText += NOBR(tr("You can download the latest version of the Nero AAC encoder from the Nero website at:")).append("<br>");
1426 messageText += "<nobr><tt>" + LINK(AboutDialog::neroAacUrl) + "</tt></nobr><br><br>";
1427 messageText += NOBR(tr("(Hint: Please ignore the name of the downloaded ZIP file and check the included 'changelog.txt' instead!)")).append("<br>");
1428 QMessageBox::information(this, tr("AAC Encoder Outdated"), messageText);
1434 if(m_settings->neroAacNotificationsEnabled() && (aacEncoder <= SettingsModel::AAC_ENCODER_NONE))
1436 QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
1437 if(appPath.isEmpty()) appPath = QCoreApplication::applicationDirPath();
1438 QString messageText;
1439 messageText += NOBR(tr("The Nero AAC encoder could not be found. AAC encoding support will be disabled.")).append("<br>");
1440 messageText += NOBR(tr("Please put 'neroAacEnc.exe', 'neroAacDec.exe' and 'neroAacTag.exe' into the LameXP directory!")).append("<br><br>");
1441 messageText += NOBR(tr("Your LameXP directory is located here:")).append("<br>");
1442 messageText += QString("<nobr><tt>%1</tt></nobr><br><br>").arg(FSLINK(QDir::toNativeSeparators(appPath)));
1443 messageText += NOBR(tr("You can download the Nero AAC encoder for free from the official Nero website at:")).append("<br>");
1444 messageText += "<nobr><tt>" + LINK(AboutDialog::neroAacUrl) + "</tt></nobr><br>";
1445 if(QMessageBox::information(this, tr("AAC Support Disabled"), messageText, tr("Discard"), tr("Don't Show Again")) == 1)
1447 m_settings->neroAacNotificationsEnabled(false);
1448 ui->actionDisableNeroAacNotifications->setChecked(!m_settings->neroAacNotificationsEnabled());
1453 //Add files from the command-line
1454 for(int i = 0; i < arguments.count() - 1; i++)
1456 QStringList addedFiles;
1457 if(!arguments[i].compare("--add", Qt::CaseInsensitive))
1459 QFileInfo currentFile(arguments[++i].trimmed());
1460 qDebug("Adding file from CLI: %s", MUTILS_UTF8(currentFile.absoluteFilePath()));
1461 addedFiles.append(currentFile.absoluteFilePath());
1463 if(!addedFiles.isEmpty())
1465 addFilesDelayed(addedFiles);
1469 //Add folders from the command-line
1470 for(int i = 0; i < arguments.count() - 1; i++)
1472 if(!arguments[i].compare("--add-folder", Qt::CaseInsensitive))
1474 QFileInfo currentFile(arguments[++i].trimmed());
1475 qDebug("Adding folder from CLI: %s", MUTILS_UTF8(currentFile.absoluteFilePath()));
1476 addFolder(currentFile.absoluteFilePath(), false, true);
1478 if(!arguments[i].compare("--add-recursive", Qt::CaseInsensitive))
1480 QFileInfo currentFile(arguments[++i].trimmed());
1481 qDebug("Adding folder recursively from CLI: %s", MUTILS_UTF8(currentFile.absoluteFilePath()));
1482 addFolder(currentFile.absoluteFilePath(), true, true);
1486 //Enable shell integration
1487 if(m_settings->shellIntegrationEnabled())
1489 ShellIntegration::install();
1492 //Make DropBox visible
1493 if(m_settings->dropBoxWidgetEnabled())
1495 m_dropBox->setVisible(true);
1502 void MainWindow::showAnnounceBox(void)
1504 const unsigned int timeout = 8U;
1506 const QString announceText = QString("%1<br><br>%2<br><nobr><tt>%3</tt></nobr><br>").arg
1508 NOBR("We are still looking for LameXP translators!"),
1509 NOBR("If you are willing to translate LameXP to your language or to complete an existing translation, please refer to:"),
1510 LINK("http://lamexp.sourceforge.net/doc/Translate.html")
1513 QMessageBox *announceBox = new QMessageBox(QMessageBox::Warning, "We want you!", announceText, QMessageBox::NoButton, this);
1514 announceBox->setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
1515 announceBox->setIconPixmap(QIcon(":/images/Announcement.png").pixmap(64,79));
1517 QTimer *timers[timeout+1];
1518 QPushButton *buttons[timeout+1];
1520 for(unsigned int i = 0; i <= timeout; i++)
1522 QString text = (i > 0) ? QString("%1 (%2)").arg(tr("Discard"), QString::number(i)) : tr("Discard");
1523 buttons[i] = announceBox->addButton(text, (i > 0) ? QMessageBox::NoRole : QMessageBox::AcceptRole);
1526 for(unsigned int i = 0; i <= timeout; i++)
1528 buttons[i]->setEnabled(i == 0);
1529 buttons[i]->setVisible(i == timeout);
1532 for(unsigned int i = 0; i < timeout; i++)
1534 timers[i] = new QTimer(this);
1535 timers[i]->setSingleShot(true);
1536 timers[i]->setInterval(1000);
1537 connect(timers[i], SIGNAL(timeout()), buttons[i+1], SLOT(hide()));
1538 connect(timers[i], SIGNAL(timeout()), buttons[i], SLOT(show()));
1541 connect(timers[i], SIGNAL(timeout()), timers[i-1], SLOT(start()));
1545 timers[timeout-1]->start();
1546 announceBox->exec();
1548 for(unsigned int i = 0; i < timeout; i++)
1551 MUTILS_DELETE(timers[i]);
1554 MUTILS_DELETE(announceBox);
1557 // =========================================================
1558 // Main button solots
1559 // =========================================================
1564 void MainWindow::encodeButtonClicked(void)
1566 static const unsigned __int64 oneGigabyte = 1073741824ui64;
1567 static const unsigned __int64 minimumFreeDiskspaceMultiplier = 2ui64;
1568 static const char *writeTestBuffer = "LAMEXP_WRITE_TEST";
1572 if(m_fileListModel->rowCount() < 1)
1574 QMessageBox::warning(this, tr("LameXP"), NOBR(tr("You must add at least one file to the list before proceeding!")));
1575 ui->tabWidget->setCurrentIndex(0);
1579 QString tempFolder = m_settings->customTempPathEnabled() ? m_settings->customTempPath() : MUtils::temp_folder();
1580 if(!QFileInfo(tempFolder).exists() || !QFileInfo(tempFolder).isDir())
1582 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)
1584 SET_CHECKBOX_STATE(ui->checkBoxUseSystemTempFolder, m_settings->customTempPathEnabledDefault());
1589 quint64 currentFreeDiskspace = 0;
1590 if(MUtils::OS::free_diskspace(tempFolder, currentFreeDiskspace))
1592 if(currentFreeDiskspace < (oneGigabyte * minimumFreeDiskspaceMultiplier))
1594 QStringList tempFolderParts = tempFolder.split("/", QString::SkipEmptyParts, Qt::CaseInsensitive);
1595 tempFolderParts.takeLast();
1596 PLAY_SOUND_OPTIONAL("whammy", false);
1597 QString lowDiskspaceMsg = QString("%1<br>%2<br><br>%3<br>%4<br>").arg
1599 NOBR(tr("There are less than %1 GB of free diskspace available on your system's TEMP folder.").arg(QString::number(minimumFreeDiskspaceMultiplier))),
1600 NOBR(tr("It is highly recommend to free up more diskspace before proceeding with the encode!")),
1601 NOBR(tr("Your TEMP folder is located at:")),
1602 QString("<nobr><tt>%1</tt></nobr>").arg(FSLINK(tempFolderParts.join("\\")))
1604 switch(QMessageBox::warning(this, tr("Low Diskspace Warning"), lowDiskspaceMsg, tr("Abort Encoding Process"), tr("Clean Disk Now"), tr("Ignore")))
1607 QProcess::startDetached(QString("%1/cleanmgr.exe").arg(MUtils::OS::known_folder(MUtils::OS::FOLDER_SYSTEMFOLDER)), QStringList() << "/D" << tempFolderParts.first());
1612 QMessageBox::warning(this, tr("Low Diskspace"), NOBR(tr("You are proceeding with low diskspace. Problems might occur!")));
1618 switch(m_settings->compressionEncoder())
1620 case SettingsModel::MP3Encoder:
1621 case SettingsModel::VorbisEncoder:
1622 case SettingsModel::AACEncoder:
1623 case SettingsModel::AC3Encoder:
1624 case SettingsModel::FLACEncoder:
1625 case SettingsModel::OpusEncoder:
1626 case SettingsModel::DCAEncoder:
1627 case SettingsModel::MACEncoder:
1628 case SettingsModel::PCMEncoder:
1631 QMessageBox::warning(this, tr("LameXP"), tr("Sorry, an unsupported encoder has been chosen!"));
1632 ui->tabWidget->setCurrentIndex(3);
1636 if(!m_settings->outputToSourceDir())
1638 QFile writeTest(QString("%1/~%2.txt").arg(m_settings->outputDir(), MUtils::rand_str()));
1639 if(!(writeTest.open(QIODevice::ReadWrite) && (writeTest.write(writeTestBuffer) == strlen(writeTestBuffer))))
1641 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!")));
1642 ui->tabWidget->setCurrentIndex(1);
1659 void MainWindow::aboutButtonClicked(void)
1665 AboutDialog *aboutBox = new AboutDialog(m_settings, this);
1667 MUTILS_DELETE(aboutBox);
1674 void MainWindow::closeButtonClicked(void)
1680 // =========================================================
1682 // =========================================================
1687 void MainWindow::tabPageChanged(int idx, const bool silent)
1691 //Update "view" menu
1692 QList<QAction*> actions = m_tabActionGroup->actions();
1693 for(int i = 0; i < actions.count(); i++)
1696 int actionIndex = actions.at(i)->data().toInt(&ok);
1697 if(ok && actionIndex == idx)
1699 actions.at(i)->setChecked(true);
1706 PLAY_SOUND_OPTIONAL("tick", true);
1709 int initialWidth = this->width();
1710 int maximumWidth = QApplication::desktop()->availableGeometry().width();
1712 //Make sure all tab headers are fully visible
1713 if(this->isVisible())
1715 int delta = ui->tabWidget->sizeHint().width() - ui->tabWidget->width();
1718 this->resize(qMin(this->width() + delta, maximumWidth), this->height());
1722 //Tab specific operations
1723 if(idx == ui->tabWidget->indexOf(ui->tabOptions) && ui->scrollArea->widget() && this->isVisible())
1725 ui->scrollArea->widget()->updateGeometry();
1726 ui->scrollArea->viewport()->updateGeometry();
1727 qApp->processEvents();
1728 int delta = ui->scrollArea->widget()->width() - ui->scrollArea->viewport()->width();
1731 this->resize(qMin(this->width() + delta, maximumWidth), this->height());
1734 else if(idx == ui->tabWidget->indexOf(ui->tabSourceFiles))
1736 m_dropNoteLabel->setGeometry(0, 0, ui->sourceFileView->width(), ui->sourceFileView->height());
1738 else if(idx == ui->tabWidget->indexOf(ui->tabOutputDir))
1740 if(!m_fileSystemModel)
1742 QTimer::singleShot(125, this, SLOT(initOutputFolderModel()));
1746 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
1750 //Center window around previous position
1751 if(initialWidth < this->width())
1753 QPoint prevPos = this->pos();
1754 int delta = (this->width() - initialWidth) >> 2;
1755 move(prevPos.x() - delta, prevPos.y());
1760 * Tab action triggered
1762 void MainWindow::tabActionActivated(QAction *action)
1764 if(action && action->data().isValid())
1767 int index = action->data().toInt(&ok);
1770 ui->tabWidget->setCurrentIndex(index);
1775 // =========================================================
1777 // =========================================================
1780 * Handle corner widget Event
1782 void MainWindow::cornerWidgetEventOccurred(QWidget *sender, QEvent *event)
1784 if(event->type() == QEvent::MouseButtonPress)
1786 QTimer::singleShot(0, this, SLOT(checkUpdatesActionActivated()));
1790 // =========================================================
1792 // =========================================================
1795 * Style action triggered
1797 void MainWindow::styleActionActivated(QAction *action)
1799 //Change style setting
1800 if(action && action->data().isValid())
1803 int actionIndex = action->data().toInt(&ok);
1806 m_settings->interfaceStyle(actionIndex);
1810 //Set up the new style
1811 switch(m_settings->interfaceStyle())
1814 if(ui->actionStyleCleanlooks->isEnabled())
1816 ui->actionStyleCleanlooks->setChecked(true);
1817 QApplication::setStyle(new QCleanlooksStyle());
1821 if(ui->actionStyleWindowsVista->isEnabled())
1823 ui->actionStyleWindowsVista->setChecked(true);
1824 QApplication::setStyle(new QWindowsVistaStyle());
1828 if(ui->actionStyleWindowsXP->isEnabled())
1830 ui->actionStyleWindowsXP->setChecked(true);
1831 QApplication::setStyle(new QWindowsXPStyle());
1835 if(ui->actionStyleWindowsClassic->isEnabled())
1837 ui->actionStyleWindowsClassic->setChecked(true);
1838 QApplication::setStyle(new QWindowsStyle());
1842 ui->actionStylePlastique->setChecked(true);
1843 QApplication::setStyle(new QPlastiqueStyle());
1847 //Force re-translate after style change
1848 if(QEvent *e = new QEvent(QEvent::LanguageChange))
1855 const type_info &styleType = typeid(*qApp->style());
1856 const bool bTransparent = ((typeid(QWindowsVistaStyle) == styleType) || (typeid(QWindowsXPStyle) == styleType));
1857 MAKE_TRANSPARENT(ui->scrollArea, bTransparent);
1859 //Also force a re-size event
1860 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
1865 * Language action triggered
1867 void MainWindow::languageActionActivated(QAction *action)
1869 if(action->data().type() == QVariant::String)
1871 QString langId = action->data().toString();
1873 if(lamexp_install_translator(langId))
1875 action->setChecked(true);
1876 ui->actionLoadTranslationFromFile->setChecked(false);
1877 m_settings->currentLanguage(langId);
1878 m_settings->currentLanguageFile(QString());
1884 * Load language from file action triggered
1886 void MainWindow::languageFromFileActionActivated(bool checked)
1888 QFileDialog dialog(this, tr("Load Translation"));
1889 dialog.setFileMode(QFileDialog::ExistingFile);
1890 dialog.setNameFilter(QString("%1 (*.qm)").arg(tr("Translation Files")));
1894 QStringList selectedFiles = dialog.selectedFiles();
1895 const QString qmFile = QFileInfo(selectedFiles.first()).canonicalFilePath();
1896 if(lamexp_install_translator_from_file(qmFile))
1898 QList<QAction*> actions = m_languageActionGroup->actions();
1899 while(!actions.isEmpty())
1901 actions.takeFirst()->setChecked(false);
1903 ui->actionLoadTranslationFromFile->setChecked(true);
1904 m_settings->currentLanguageFile(qmFile);
1908 languageActionActivated(m_languageActionGroup->actions().first());
1913 // =========================================================
1915 // =========================================================
1918 * Disable update reminder action
1920 void MainWindow::disableUpdateReminderActionTriggered(bool checked)
1924 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))
1926 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!"))));
1927 m_settings->autoUpdateEnabled(false);
1931 m_settings->autoUpdateEnabled(true);
1936 QMessageBox::information(this, tr("Update Reminder"), NOBR(tr("The update reminder has been re-enabled.")));
1937 m_settings->autoUpdateEnabled(true);
1940 ui->actionDisableUpdateReminder->setChecked(!m_settings->autoUpdateEnabled());
1944 * Disable sound effects action
1946 void MainWindow::disableSoundsActionTriggered(bool checked)
1950 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))
1952 QMessageBox::information(this, tr("Sound Effects"), NOBR(tr("All sound effects have been disabled.")));
1953 m_settings->soundsEnabled(false);
1957 m_settings->soundsEnabled(true);
1962 QMessageBox::information(this, tr("Sound Effects"), NOBR(tr("The sound effects have been re-enabled.")));
1963 m_settings->soundsEnabled(true);
1966 ui->actionDisableSounds->setChecked(!m_settings->soundsEnabled());
1970 * Disable Nero AAC encoder action
1972 void MainWindow::disableNeroAacNotificationsActionTriggered(bool checked)
1976 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))
1978 QMessageBox::information(this, tr("Nero AAC Notifications"), NOBR(tr("All Nero AAC Encoder notifications have been disabled.")));
1979 m_settings->neroAacNotificationsEnabled(false);
1983 m_settings->neroAacNotificationsEnabled(true);
1988 QMessageBox::information(this, tr("Nero AAC Notifications"), NOBR(tr("The Nero AAC Encoder notifications have been re-enabled.")));
1989 m_settings->neroAacNotificationsEnabled(true);
1992 ui->actionDisableNeroAacNotifications->setChecked(!m_settings->neroAacNotificationsEnabled());
1996 * Disable slow startup action
1998 void MainWindow::disableSlowStartupNotificationsActionTriggered(bool checked)
2002 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))
2004 QMessageBox::information(this, tr("Slow Startup Notifications"), NOBR(tr("The slow startup notifications have been disabled.")));
2005 m_settings->antivirNotificationsEnabled(false);
2009 m_settings->antivirNotificationsEnabled(true);
2014 QMessageBox::information(this, tr("Slow Startup Notifications"), NOBR(tr("The slow startup notifications have been re-enabled.")));
2015 m_settings->antivirNotificationsEnabled(true);
2018 ui->actionDisableSlowStartupNotifications->setChecked(!m_settings->antivirNotificationsEnabled());
2022 * Import a Cue Sheet file
2024 void MainWindow::importCueSheetActionTriggered(bool checked)
2033 QString selectedCueFile;
2035 if(lamexp_themes_enabled())
2037 selectedCueFile = QFileDialog::getOpenFileName(this, tr("Open Cue Sheet"), m_settings->mostRecentInputPath(), QString("%1 (*.cue)").arg(tr("Cue Sheet File")));
2041 QFileDialog dialog(this, tr("Open Cue Sheet"));
2042 dialog.setFileMode(QFileDialog::ExistingFile);
2043 dialog.setNameFilter(QString("%1 (*.cue)").arg(tr("Cue Sheet File")));
2044 dialog.setDirectory(m_settings->mostRecentInputPath());
2047 selectedCueFile = dialog.selectedFiles().first();
2051 if(!selectedCueFile.isEmpty())
2053 m_settings->mostRecentInputPath(QFileInfo(selectedCueFile).canonicalPath());
2054 CueImportDialog *cueImporter = new CueImportDialog(this, m_fileListModel, selectedCueFile, m_settings);
2055 result = cueImporter->exec();
2056 MUTILS_DELETE(cueImporter);
2059 if(result == QDialog::Accepted)
2061 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
2062 ui->sourceFileView->update();
2063 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
2064 ui->sourceFileView->scrollToBottom();
2065 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
2068 if(result != (-1)) break;
2074 * Show the "drop box" widget
2076 void MainWindow::showDropBoxWidgetActionTriggered(bool checked)
2078 m_settings->dropBoxWidgetEnabled(true);
2080 if(!m_dropBox->isVisible())
2083 QTimer::singleShot(2500, m_dropBox, SLOT(showToolTip()));
2086 lamexp_blink_window(m_dropBox);
2090 * Check for beta (pre-release) updates
2092 void MainWindow::checkForBetaUpdatesActionTriggered(bool checked)
2094 bool checkUpdatesNow = false;
2098 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))
2100 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")))
2102 checkUpdatesNow = true;
2104 m_settings->autoUpdateCheckBeta(true);
2108 m_settings->autoUpdateCheckBeta(false);
2113 QMessageBox::information(this, tr("Beta Updates"), NOBR(tr("LameXP will <i>not</i> check for Beta (pre-release) updates from now on.")));
2114 m_settings->autoUpdateCheckBeta(false);
2117 ui->actionCheckForBetaUpdates->setChecked(m_settings->autoUpdateCheckBeta());
2121 if(checkForUpdates())
2123 QApplication::quit();
2129 * Hibernate computer action
2131 void MainWindow::hibernateComputerActionTriggered(bool checked)
2135 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))
2137 QMessageBox::information(this, tr("Hibernate Computer"), NOBR(tr("LameXP will hibernate the computer on shutdown from now on.")));
2138 m_settings->hibernateComputer(true);
2142 m_settings->hibernateComputer(false);
2147 QMessageBox::information(this, tr("Hibernate Computer"), NOBR(tr("LameXP will <i>not</i> hibernate the computer on shutdown from now on.")));
2148 m_settings->hibernateComputer(false);
2151 ui->actionHibernateComputer->setChecked(m_settings->hibernateComputer());
2155 * Disable shell integration action
2157 void MainWindow::disableShellIntegrationActionTriggered(bool checked)
2161 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))
2163 ShellIntegration::remove();
2164 QMessageBox::information(this, tr("Shell Integration"), NOBR(tr("The LameXP shell integration has been disabled.")));
2165 m_settings->shellIntegrationEnabled(false);
2169 m_settings->shellIntegrationEnabled(true);
2174 ShellIntegration::install();
2175 QMessageBox::information(this, tr("Shell Integration"), NOBR(tr("The LameXP shell integration has been re-enabled.")));
2176 m_settings->shellIntegrationEnabled(true);
2179 ui->actionDisableShellIntegration->setChecked(!m_settings->shellIntegrationEnabled());
2181 if(lamexp_portable_mode() && ui->actionDisableShellIntegration->isChecked())
2183 ui->actionDisableShellIntegration->setEnabled(false);
2187 // =========================================================
2189 // =========================================================
2192 * Visit homepage action
2194 void MainWindow::visitHomepageActionActivated(void)
2196 if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
2198 if(action->data().isValid() && (action->data().type() == QVariant::String))
2200 QDesktopServices::openUrl(QUrl(action->data().toString()));
2208 void MainWindow::documentActionActivated(void)
2210 if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
2212 if(action->data().isValid() && (action->data().type() == QVariant::String))
2214 QFileInfo document(action->data().toString());
2215 QFileInfo resource(QString(":/doc/%1.html").arg(document.baseName()));
2216 if(document.exists() && document.isFile() && (document.size() == resource.size()))
2218 QDesktopServices::openUrl(QUrl::fromLocalFile(document.canonicalFilePath()));
2222 QFile source(resource.filePath());
2223 QFile output(QString("%1/%2.%3.html").arg(MUtils::temp_folder(), document.baseName(), MUtils::rand_str().left(8)));
2224 if(source.open(QIODevice::ReadOnly) && output.open(QIODevice::ReadWrite))
2226 output.write(source.readAll());
2227 action->setData(output.fileName());
2230 QDesktopServices::openUrl(QUrl::fromLocalFile(output.fileName()));
2238 * Check for updates action
2240 void MainWindow::checkUpdatesActionActivated(void)
2247 bFlag = checkForUpdates();
2252 QApplication::quit();
2256 // =========================================================
2257 // Source file slots
2258 // =========================================================
2261 * Add file(s) button
2263 void MainWindow::addFilesButtonClicked(void)
2269 if(lamexp_themes_enabled())
2271 QStringList fileTypeFilters = DecoderRegistry::getSupportedTypes();
2272 QStringList selectedFiles = QFileDialog::getOpenFileNames(this, tr("Add file(s)"), m_settings->mostRecentInputPath(), fileTypeFilters.join(";;"));
2273 if(!selectedFiles.isEmpty())
2275 m_settings->mostRecentInputPath(QFileInfo(selectedFiles.first()).canonicalPath());
2276 addFiles(selectedFiles);
2281 QFileDialog dialog(this, tr("Add file(s)"));
2282 QStringList fileTypeFilters = DecoderRegistry::getSupportedTypes();
2283 dialog.setFileMode(QFileDialog::ExistingFiles);
2284 dialog.setNameFilter(fileTypeFilters.join(";;"));
2285 dialog.setDirectory(m_settings->mostRecentInputPath());
2288 QStringList selectedFiles = dialog.selectedFiles();
2289 if(!selectedFiles.isEmpty())
2291 m_settings->mostRecentInputPath(QFileInfo(selectedFiles.first()).canonicalPath());
2292 addFiles(selectedFiles);
2300 * Open folder action
2302 void MainWindow::openFolderActionActivated(void)
2305 QString selectedFolder;
2307 if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
2311 if(lamexp_themes_enabled())
2313 selectedFolder = QFileDialog::getExistingDirectory(this, tr("Add Folder"), m_settings->mostRecentInputPath());
2317 QFileDialog dialog(this, tr("Add Folder"));
2318 dialog.setFileMode(QFileDialog::DirectoryOnly);
2319 dialog.setDirectory(m_settings->mostRecentInputPath());
2322 selectedFolder = dialog.selectedFiles().first();
2326 if(!selectedFolder.isEmpty())
2328 m_settings->mostRecentInputPath(QDir(selectedFolder).canonicalPath());
2329 addFolder(selectedFolder, action->data().toBool());
2336 * Remove file button
2338 void MainWindow::removeFileButtonClicked(void)
2340 if(ui->sourceFileView->currentIndex().isValid())
2342 int iRow = ui->sourceFileView->currentIndex().row();
2343 m_fileListModel->removeFile(ui->sourceFileView->currentIndex());
2344 ui->sourceFileView->selectRow(iRow < m_fileListModel->rowCount() ? iRow : m_fileListModel->rowCount()-1);
2349 * Clear files button
2351 void MainWindow::clearFilesButtonClicked(void)
2353 m_fileListModel->clearFiles();
2357 * Move file up button
2359 void MainWindow::fileUpButtonClicked(void)
2361 if(ui->sourceFileView->currentIndex().isValid())
2363 int iRow = ui->sourceFileView->currentIndex().row() - 1;
2364 m_fileListModel->moveFile(ui->sourceFileView->currentIndex(), -1);
2365 ui->sourceFileView->selectRow(iRow >= 0 ? iRow : 0);
2370 * Move file down button
2372 void MainWindow::fileDownButtonClicked(void)
2374 if(ui->sourceFileView->currentIndex().isValid())
2376 int iRow = ui->sourceFileView->currentIndex().row() + 1;
2377 m_fileListModel->moveFile(ui->sourceFileView->currentIndex(), 1);
2378 ui->sourceFileView->selectRow(iRow < m_fileListModel->rowCount() ? iRow : m_fileListModel->rowCount()-1);
2383 * Show details button
2385 void MainWindow::showDetailsButtonClicked(void)
2390 MetaInfoDialog *metaInfoDialog = new MetaInfoDialog(this);
2391 QModelIndex index = ui->sourceFileView->currentIndex();
2393 while(index.isValid())
2397 index = m_fileListModel->index(index.row() + 1, index.column());
2398 ui->sourceFileView->selectRow(index.row());
2402 index = m_fileListModel->index(index.row() - 1, index.column());
2403 ui->sourceFileView->selectRow(index.row());
2406 AudioFileModel &file = (*m_fileListModel)[index];
2409 iResult = metaInfoDialog->exec(file, index.row() > 0, index.row() < m_fileListModel->rowCount() - 1);
2412 //Copy all info to Meta Info tab
2413 if(iResult == INT_MAX)
2415 m_metaInfoModel->assignInfoFrom(file);
2416 ui->tabWidget->setCurrentIndex(ui->tabWidget->indexOf(ui->tabMetaData));
2423 MUTILS_DELETE(metaInfoDialog);
2424 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
2425 sourceFilesScrollbarMoved(0);
2429 * Show context menu for source files
2431 void MainWindow::sourceFilesContextMenu(const QPoint &pos)
2433 QAbstractScrollArea *scrollArea = dynamic_cast<QAbstractScrollArea*>(QObject::sender());
2434 QWidget *sender = scrollArea ? scrollArea->viewport() : dynamic_cast<QWidget*>(QObject::sender());
2438 if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0)
2440 m_sourceFilesContextMenu->popup(sender->mapToGlobal(pos));
2446 * Scrollbar of source files moved
2448 void MainWindow::sourceFilesScrollbarMoved(int)
2450 ui->sourceFileView->resizeColumnToContents(0);
2454 * Open selected file in external player
2456 void MainWindow::previewContextActionTriggered(void)
2458 QModelIndex index = ui->sourceFileView->currentIndex();
2459 if(!index.isValid())
2464 if(!MUtils::OS::open_media_file(m_fileListModel->getFile(index).filePath()))
2466 qDebug("Player not found, falling back to default application...");
2467 QDesktopServices::openUrl(QString("file:///").append(m_fileListModel->getFile(index).filePath()));
2472 * Find selected file in explorer
2474 void MainWindow::findFileContextActionTriggered(void)
2476 QModelIndex index = ui->sourceFileView->currentIndex();
2479 QString systemRootPath;
2481 QDir systemRoot(MUtils::OS::known_folder(MUtils::OS::FOLDER_SYSTEMFOLDER));
2482 if(systemRoot.exists() && systemRoot.cdUp())
2484 systemRootPath = systemRoot.canonicalPath();
2487 if(!systemRootPath.isEmpty())
2489 QFileInfo explorer(QString("%1/explorer.exe").arg(systemRootPath));
2490 if(explorer.exists() && explorer.isFile())
2492 QProcess::execute(explorer.canonicalFilePath(), QStringList() << "/select," << QDir::toNativeSeparators(m_fileListModel->getFile(index).filePath()));
2498 qWarning("SystemRoot directory could not be detected!");
2504 * Add all dropped files
2506 void MainWindow::handleDroppedFiles(void)
2510 static const int MIN_COUNT = 16;
2511 const QString bannerText = tr("Loading dropped files or folders, please wait...");
2512 bool bUseBanner = false;
2514 SHOW_BANNER_CONDITIONALLY(bUseBanner, (m_droppedFileList->count() >= MIN_COUNT), bannerText);
2516 QStringList droppedFiles;
2517 while(!m_droppedFileList->isEmpty())
2519 QFileInfo file(m_droppedFileList->takeFirst().toLocalFile());
2520 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
2529 qDebug("Dropped File: %s", MUTILS_UTF8(file.canonicalFilePath()));
2530 droppedFiles << file.canonicalFilePath();
2536 qDebug("Dropped Folder: %s", MUTILS_UTF8(file.canonicalFilePath()));
2537 QFileInfoList list = QDir(file.canonicalFilePath()).entryInfoList(QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks);
2538 if(list.count() > 0)
2540 SHOW_BANNER_CONDITIONALLY(bUseBanner, (list.count() >= MIN_COUNT), bannerText);
2541 for(QFileInfoList::ConstIterator iter = list.constBegin(); iter != list.constEnd(); iter++)
2543 droppedFiles << (*iter).canonicalFilePath();
2548 list = QDir(file.canonicalFilePath()).entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks);
2549 SHOW_BANNER_CONDITIONALLY(bUseBanner, (list.count() >= MIN_COUNT), bannerText);
2550 for(QFileInfoList::ConstIterator iter = list.constBegin(); iter != list.constEnd(); iter++)
2552 qDebug("Descending to Folder: %s", MUTILS_UTF8((*iter).canonicalFilePath()));
2553 m_droppedFileList->prepend(QUrl::fromLocalFile((*iter).canonicalFilePath()));
2564 if(!droppedFiles.isEmpty())
2566 addFiles(droppedFiles);
2571 * Add all pending files
2573 void MainWindow::handleDelayedFiles(void)
2575 m_delayedFileTimer->stop();
2577 if(m_delayedFileList->isEmpty())
2584 m_delayedFileTimer->start(5000);
2588 WITH_BLOCKED_SIGNALS(ui->tabWidget, setCurrentIndex, 0);
2589 tabPageChanged(ui->tabWidget->currentIndex(), true);
2591 QStringList selectedFiles;
2592 while(!m_delayedFileList->isEmpty())
2594 QFileInfo currentFile = QFileInfo(m_delayedFileList->takeFirst());
2595 if(!currentFile.exists() || !currentFile.isFile())
2599 selectedFiles << currentFile.canonicalFilePath();
2602 addFiles(selectedFiles);
2606 * Export Meta tags to CSV file
2608 void MainWindow::exportCsvContextActionTriggered(void)
2612 QString selectedCsvFile;
2614 if(lamexp_themes_enabled())
2616 selectedCsvFile = QFileDialog::getSaveFileName(this, tr("Save CSV file"), m_settings->mostRecentInputPath(), QString("%1 (*.csv)").arg(tr("CSV File")));
2620 QFileDialog dialog(this, tr("Save CSV file"));
2621 dialog.setFileMode(QFileDialog::AnyFile);
2622 dialog.setAcceptMode(QFileDialog::AcceptSave);
2623 dialog.setNameFilter(QString("%1 (*.csv)").arg(tr("CSV File")));
2624 dialog.setDirectory(m_settings->mostRecentInputPath());
2627 selectedCsvFile = dialog.selectedFiles().first();
2631 if(!selectedCsvFile.isEmpty())
2633 m_settings->mostRecentInputPath(QFileInfo(selectedCsvFile).canonicalPath());
2634 switch(m_fileListModel->exportToCsv(selectedCsvFile))
2636 case FileListModel::CsvError_NoTags:
2637 QMessageBox::critical(this, tr("CSV Export"), NOBR(tr("Sorry, there are no meta tags that can be exported!")));
2639 case FileListModel::CsvError_FileOpen:
2640 QMessageBox::critical(this, tr("CSV Export"), NOBR(tr("Sorry, failed to open CSV file for writing!")));
2642 case FileListModel::CsvError_FileWrite:
2643 QMessageBox::critical(this, tr("CSV Export"), NOBR(tr("Sorry, failed to write to the CSV file!")));
2645 case FileListModel::CsvError_OK:
2646 QMessageBox::information(this, tr("CSV Export"), NOBR(tr("The CSV files was created successfully!")));
2649 qWarning("exportToCsv: Unknown return code!");
2657 * Import Meta tags from CSV file
2659 void MainWindow::importCsvContextActionTriggered(void)
2663 QString selectedCsvFile;
2665 if(lamexp_themes_enabled())
2667 selectedCsvFile = QFileDialog::getOpenFileName(this, tr("Open CSV file"), m_settings->mostRecentInputPath(), QString("%1 (*.csv)").arg(tr("CSV File")));
2671 QFileDialog dialog(this, tr("Open CSV file"));
2672 dialog.setFileMode(QFileDialog::ExistingFile);
2673 dialog.setNameFilter(QString("%1 (*.csv)").arg(tr("CSV File")));
2674 dialog.setDirectory(m_settings->mostRecentInputPath());
2677 selectedCsvFile = dialog.selectedFiles().first();
2681 if(!selectedCsvFile.isEmpty())
2683 m_settings->mostRecentInputPath(QFileInfo(selectedCsvFile).canonicalPath());
2684 switch(m_fileListModel->importFromCsv(this, selectedCsvFile))
2686 case FileListModel::CsvError_FileOpen:
2687 QMessageBox::critical(this, tr("CSV Import"), NOBR(tr("Sorry, failed to open CSV file for reading!")));
2689 case FileListModel::CsvError_FileRead:
2690 QMessageBox::critical(this, tr("CSV Import"), NOBR(tr("Sorry, failed to read from the CSV file!")));
2692 case FileListModel::CsvError_NoTags:
2693 QMessageBox::critical(this, tr("CSV Import"), NOBR(tr("Sorry, the CSV file does not contain any known fields!")));
2695 case FileListModel::CsvError_Incomplete:
2696 QMessageBox::warning(this, tr("CSV Import"), NOBR(tr("CSV file is incomplete. Not all files were updated!")));
2698 case FileListModel::CsvError_OK:
2699 QMessageBox::information(this, tr("CSV Import"), NOBR(tr("The CSV files was imported successfully!")));
2701 case FileListModel::CsvError_Aborted:
2702 /* User aborted, ignore! */
2705 qWarning("exportToCsv: Unknown return code!");
2712 * Show or hide Drag'n'Drop notice after model reset
2714 void MainWindow::sourceModelChanged(void)
2716 m_dropNoteLabel->setVisible(m_fileListModel->rowCount() <= 0);
2719 // =========================================================
2720 // Output folder slots
2721 // =========================================================
2724 * Output folder changed (mouse clicked)
2726 void MainWindow::outputFolderViewClicked(const QModelIndex &index)
2728 if(index.isValid() && (ui->outputFolderView->currentIndex() != index))
2730 ui->outputFolderView->setCurrentIndex(index);
2733 if(m_fileSystemModel && index.isValid())
2735 QString selectedDir = m_fileSystemModel->filePath(index);
2736 if(selectedDir.length() < 3) selectedDir.append(QDir::separator());
2737 ui->outputFolderLabel->setText(QDir::toNativeSeparators(selectedDir));
2738 ui->outputFolderLabel->setToolTip(ui->outputFolderLabel->text());
2739 m_settings->outputDir(selectedDir);
2743 ui->outputFolderLabel->setText(QDir::toNativeSeparators(m_settings->outputDir()));
2744 ui->outputFolderLabel->setToolTip(ui->outputFolderLabel->text());
2749 * Output folder changed (mouse moved)
2751 void MainWindow::outputFolderViewMoved(const QModelIndex &index)
2753 if(QApplication::mouseButtons() & Qt::LeftButton)
2755 outputFolderViewClicked(index);
2760 * Goto desktop button
2762 void MainWindow::gotoDesktopButtonClicked(void)
2764 if(!m_fileSystemModel)
2766 qWarning("File system model not initialized yet!");
2770 QString desktopPath = QDesktopServices::storageLocation(QDesktopServices::DesktopLocation);
2772 if(!desktopPath.isEmpty() && QDir(desktopPath).exists())
2774 ui->outputFolderView->setCurrentIndex(m_fileSystemModel->index(desktopPath));
2775 outputFolderViewClicked(ui->outputFolderView->currentIndex());
2776 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2780 ui->buttonGotoDesktop->setEnabled(false);
2785 * Goto home folder button
2787 void MainWindow::gotoHomeFolderButtonClicked(void)
2789 if(!m_fileSystemModel)
2791 qWarning("File system model not initialized yet!");
2795 QString homePath = QDesktopServices::storageLocation(QDesktopServices::HomeLocation);
2797 if(!homePath.isEmpty() && QDir(homePath).exists())
2799 ui->outputFolderView->setCurrentIndex(m_fileSystemModel->index(homePath));
2800 outputFolderViewClicked(ui->outputFolderView->currentIndex());
2801 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2805 ui->buttonGotoHome->setEnabled(false);
2810 * Goto music folder button
2812 void MainWindow::gotoMusicFolderButtonClicked(void)
2814 if(!m_fileSystemModel)
2816 qWarning("File system model not initialized yet!");
2820 QString musicPath = QDesktopServices::storageLocation(QDesktopServices::MusicLocation);
2822 if(!musicPath.isEmpty() && QDir(musicPath).exists())
2824 ui->outputFolderView->setCurrentIndex(m_fileSystemModel->index(musicPath));
2825 outputFolderViewClicked(ui->outputFolderView->currentIndex());
2826 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2830 ui->buttonGotoMusic->setEnabled(false);
2835 * Goto music favorite output folder
2837 void MainWindow::gotoFavoriteFolder(void)
2839 if(!m_fileSystemModel)
2841 qWarning("File system model not initialized yet!");
2845 QAction *item = dynamic_cast<QAction*>(QObject::sender());
2849 QDir path(item->data().toString());
2852 ui->outputFolderView->setCurrentIndex(m_fileSystemModel->index(path.canonicalPath()));
2853 outputFolderViewClicked(ui->outputFolderView->currentIndex());
2854 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2858 lamexp_beep(lamexp_beep_error);
2859 m_outputFolderFavoritesMenu->removeAction(item);
2860 item->deleteLater();
2866 * Make folder button
2868 void MainWindow::makeFolderButtonClicked(void)
2872 if(!m_fileSystemModel)
2874 qWarning("File system model not initialized yet!");
2878 QDir basePath(m_fileSystemModel->fileInfo(ui->outputFolderView->currentIndex()).absoluteFilePath());
2879 QString suggestedName = tr("New Folder");
2881 if(!m_metaData->artist().isEmpty() && !m_metaData->album().isEmpty())
2883 suggestedName = QString("%1 - %2").arg(m_metaData->artist(),m_metaData->album());
2885 else if(!m_metaData->artist().isEmpty())
2887 suggestedName = m_metaData->artist();
2889 else if(!m_metaData->album().isEmpty())
2891 suggestedName =m_metaData->album();
2895 for(int i = 0; i < m_fileListModel->rowCount(); i++)
2897 const AudioFileModel &audioFile = m_fileListModel->getFile(m_fileListModel->index(i, 0));
2898 const AudioFileModel_MetaInfo &fileMetaInfo = audioFile.metaInfo();
2900 if(!fileMetaInfo.album().isEmpty() || !fileMetaInfo.artist().isEmpty())
2902 if(!fileMetaInfo.artist().isEmpty() && !fileMetaInfo.album().isEmpty())
2904 suggestedName = QString("%1 - %2").arg(fileMetaInfo.artist(), fileMetaInfo.album());
2906 else if(!fileMetaInfo.artist().isEmpty())
2908 suggestedName = fileMetaInfo.artist();
2910 else if(!fileMetaInfo.album().isEmpty())
2912 suggestedName = fileMetaInfo.album();
2919 suggestedName = lamexp_clean_filename(suggestedName);
2923 bool bApplied = false;
2924 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();
2928 folderName = lamexp_clean_filepath(folderName.simplified());
2930 if(folderName.isEmpty())
2932 lamexp_beep(lamexp_beep_error);
2937 QString newFolder = folderName;
2939 while(basePath.exists(newFolder))
2941 newFolder = QString(folderName).append(QString().sprintf(" (%d)", ++i));
2944 if(basePath.mkpath(newFolder))
2946 QDir createdDir = basePath;
2947 if(createdDir.cd(newFolder))
2949 QModelIndex newIndex = m_fileSystemModel->index(createdDir.canonicalPath());
2950 ui->outputFolderView->setCurrentIndex(newIndex);
2951 outputFolderViewClicked(newIndex);
2952 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2957 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!")));
2965 * Output to source dir changed
2967 void MainWindow::saveToSourceFolderChanged(void)
2969 m_settings->outputToSourceDir(ui->saveToSourceFolderCheckBox->isChecked());
2973 * Prepend relative source file path to output file name changed
2975 void MainWindow::prependRelativePathChanged(void)
2977 m_settings->prependRelativeSourcePath(ui->prependRelativePathCheckBox->isChecked());
2981 * Show context menu for output folder
2983 void MainWindow::outputFolderContextMenu(const QPoint &pos)
2985 QAbstractScrollArea *scrollArea = dynamic_cast<QAbstractScrollArea*>(QObject::sender());
2986 QWidget *sender = scrollArea ? scrollArea->viewport() : dynamic_cast<QWidget*>(QObject::sender());
2988 if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0)
2990 m_outputFolderContextMenu->popup(sender->mapToGlobal(pos));
2995 * Show selected folder in explorer
2997 void MainWindow::showFolderContextActionTriggered(void)
2999 if(!m_fileSystemModel)
3001 qWarning("File system model not initialized yet!");
3005 QString path = QDir::toNativeSeparators(m_fileSystemModel->filePath(ui->outputFolderView->currentIndex()));
3006 if(!path.endsWith(QDir::separator())) path.append(QDir::separator());
3007 MUtils::OS::shell_open(this, path, true);
3011 * Refresh the directory outline
3013 void MainWindow::refreshFolderContextActionTriggered(void)
3015 //force re-initialization
3016 QTimer::singleShot(0, this, SLOT(initOutputFolderModel()));
3020 * Go one directory up
3022 void MainWindow::goUpFolderContextActionTriggered(void)
3024 QModelIndex current = ui->outputFolderView->currentIndex();
3025 if(current.isValid())
3027 QModelIndex parent = current.parent();
3028 if(parent.isValid())
3031 ui->outputFolderView->setCurrentIndex(parent);
3032 outputFolderViewClicked(parent);
3036 lamexp_beep(lamexp_beep_warning);
3038 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
3043 * Add current folder to favorites
3045 void MainWindow::addFavoriteFolderActionTriggered(void)
3047 QString path = m_fileSystemModel->filePath(ui->outputFolderView->currentIndex());
3048 QStringList favorites = m_settings->favoriteOutputFolders().split("|", QString::SkipEmptyParts);
3050 if(!favorites.contains(path, Qt::CaseInsensitive))
3052 favorites.append(path);
3053 while(favorites.count() > 6) favorites.removeFirst();
3057 lamexp_beep(lamexp_beep_warning);
3060 m_settings->favoriteOutputFolders(favorites.join("|"));
3065 * Output folder edit finished
3067 void MainWindow::outputFolderEditFinished(void)
3069 if(ui->outputFolderEdit->isHidden())
3071 return; //Not currently in edit mode!
3076 QString text = QDir::fromNativeSeparators(ui->outputFolderEdit->text().trimmed());
3077 while(text.startsWith('"') || text.startsWith('/')) text = text.right(text.length() - 1).trimmed();
3078 while(text.endsWith('"') || text.endsWith('/')) text = text.left(text.length() - 1).trimmed();
3080 static const char *str = "?*<>|\"";
3081 for(size_t i = 0; str[i]; i++) text.replace(str[i], "_");
3083 if(!((text.length() >= 2) && text.at(0).isLetter() && text.at(1) == QChar(':')))
3085 text = QString("%1/%2").arg(QDir::fromNativeSeparators(ui->outputFolderLabel->text()), text);
3088 if(text.length() == 2) text += "/"; /* "X:" => "X:/" */
3090 while(text.length() > 2)
3092 QFileInfo info(text);
3093 if(info.exists() && info.isDir())
3095 QModelIndex index = m_fileSystemModel->index(QFileInfo(info.canonicalFilePath()).absoluteFilePath());
3099 ui->outputFolderView->setCurrentIndex(index);
3100 outputFolderViewClicked(index);
3104 else if(info.exists() && info.isFile())
3106 QModelIndex index = m_fileSystemModel->index(QFileInfo(info.canonicalPath()).absoluteFilePath());
3110 ui->outputFolderView->setCurrentIndex(index);
3111 outputFolderViewClicked(index);
3116 text = text.left(text.length() - 1).trimmed();
3119 ui->outputFolderEdit->setVisible(false);
3120 ui->outputFolderLabel->setVisible(true);
3121 ui->outputFolderView->setEnabled(true);
3123 if(!ok) lamexp_beep(lamexp_beep_error);
3124 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
3128 * Initialize file system model
3130 void MainWindow::initOutputFolderModel(void)
3132 if(m_outputFolderNoteBox->isHidden())
3134 m_outputFolderNoteBox->show();
3135 m_outputFolderNoteBox->repaint();
3136 m_outputFolderViewInitCounter = 4;
3138 if(m_fileSystemModel)
3140 SET_MODEL(ui->outputFolderView, NULL);
3141 MUTILS_DELETE(m_fileSystemModel);
3142 ui->outputFolderView->repaint();
3145 if(m_fileSystemModel = new QFileSystemModelEx())
3147 m_fileSystemModel->installEventFilter(this);
3148 connect(m_fileSystemModel, SIGNAL(directoryLoaded(QString)), this, SLOT(outputFolderDirectoryLoaded(QString)));
3149 connect(m_fileSystemModel, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(outputFolderRowsInserted(QModelIndex,int,int)));
3151 SET_MODEL(ui->outputFolderView, m_fileSystemModel);
3152 ui->outputFolderView->header()->setStretchLastSection(true);
3153 ui->outputFolderView->header()->hideSection(1);
3154 ui->outputFolderView->header()->hideSection(2);
3155 ui->outputFolderView->header()->hideSection(3);
3157 m_fileSystemModel->setRootPath("");
3158 QModelIndex index = m_fileSystemModel->index(m_settings->outputDir());
3159 if(index.isValid()) ui->outputFolderView->setCurrentIndex(index);
3160 outputFolderViewClicked(ui->outputFolderView->currentIndex());
3163 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
3164 QTimer::singleShot(125, this, SLOT(initOutputFolderModel_doAsync()));
3169 * Initialize file system model (do NOT call this one directly!)
3171 void MainWindow::initOutputFolderModel_doAsync(void)
3173 if(m_outputFolderViewInitCounter > 0)
3175 m_outputFolderViewInitCounter--;
3176 QTimer::singleShot(125, this, SLOT(initOutputFolderModel_doAsync()));
3180 QTimer::singleShot(125, m_outputFolderNoteBox, SLOT(hide()));
3181 ui->outputFolderView->setFocus();
3186 * Center current folder in view
3188 void MainWindow::centerOutputFolderModel(void)
3190 if(ui->outputFolderView->isVisible())
3192 centerOutputFolderModel_doAsync();
3193 QTimer::singleShot(125, this, SLOT(centerOutputFolderModel_doAsync()));
3198 * Center current folder in view (do NOT call this one directly!)
3200 void MainWindow::centerOutputFolderModel_doAsync(void)
3202 if(ui->outputFolderView->isVisible())
3204 m_outputFolderViewCentering = true;
3205 const QModelIndex index = ui->outputFolderView->currentIndex();
3206 ui->outputFolderView->scrollTo(index, QAbstractItemView::PositionAtCenter);
3207 ui->outputFolderView->setFocus();
3212 * File system model asynchronously loaded a dir
3214 void MainWindow::outputFolderDirectoryLoaded(const QString &path)
3216 if(m_outputFolderViewCentering)
3218 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
3223 * File system model inserted new items
3225 void MainWindow::outputFolderRowsInserted(const QModelIndex &parent, int start, int end)
3227 if(m_outputFolderViewCentering)
3229 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
3234 * Directory view item was expanded by user
3236 void MainWindow::outputFolderItemExpanded(const QModelIndex &item)
3238 //We need to stop centering as soon as the user has expanded an item manually!
3239 m_outputFolderViewCentering = false;
3243 * View event for output folder control occurred
3245 void MainWindow::outputFolderViewEventOccurred(QWidget *sender, QEvent *event)
3247 switch(event->type())
3251 case QEvent::KeyPress:
3252 case QEvent::KeyRelease:
3253 case QEvent::FocusIn:
3254 case QEvent::FocusOut:
3255 case QEvent::TouchEnd:
3256 outputFolderViewClicked(ui->outputFolderView->currentIndex());
3262 * Mouse event for output folder control occurred
3264 void MainWindow::outputFolderMouseEventOccurred(QWidget *sender, QEvent *event)
3266 QMouseEvent *mouseEvent = dynamic_cast<QMouseEvent*>(event);
3267 QPoint pos = (mouseEvent) ? mouseEvent->pos() : QPoint();
3269 if(sender == ui->outputFolderLabel)
3271 switch(event->type())
3273 case QEvent::MouseButtonPress:
3274 if(mouseEvent && (mouseEvent->button() == Qt::LeftButton))
3276 QString path = ui->outputFolderLabel->text();
3277 if(!path.endsWith(QDir::separator())) path.append(QDir::separator());
3278 MUtils::OS::shell_open(this, path, true);
3282 ui->outputFolderLabel->setForegroundRole(QPalette::Link);
3285 ui->outputFolderLabel->setForegroundRole(QPalette::WindowText);
3290 if((sender == ui->outputFoldersFovoritesLabel) || (sender == ui->outputFoldersEditorLabel) || (sender == ui->outputFoldersGoUpLabel))
3292 const type_info &styleType = typeid(*qApp->style());
3293 if((typeid(QPlastiqueStyle) == styleType) || (typeid(QWindowsStyle) == styleType))
3295 switch(event->type())
3298 dynamic_cast<QLabel*>(sender)->setFrameShadow(ui->outputFolderView->isEnabled() ? QFrame::Raised : QFrame::Plain);
3300 case QEvent::MouseButtonPress:
3301 dynamic_cast<QLabel*>(sender)->setFrameShadow(ui->outputFolderView->isEnabled() ? QFrame::Sunken : QFrame::Plain);
3303 case QEvent::MouseButtonRelease:
3304 dynamic_cast<QLabel*>(sender)->setFrameShadow(ui->outputFolderView->isEnabled() ? QFrame::Raised : QFrame::Plain);
3307 dynamic_cast<QLabel*>(sender)->setFrameShadow(ui->outputFolderView->isEnabled() ? QFrame::Plain : QFrame::Plain);
3313 dynamic_cast<QLabel*>(sender)->setFrameShadow(QFrame::Plain);
3316 if((event->type() == QEvent::MouseButtonRelease) && ui->outputFolderView->isEnabled() && (mouseEvent))
3318 if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0 && mouseEvent->button() != Qt::MidButton)
3320 if(sender == ui->outputFoldersFovoritesLabel)
3322 m_outputFolderFavoritesMenu->popup(sender->mapToGlobal(pos));
3324 else if(sender == ui->outputFoldersEditorLabel)
3326 ui->outputFolderView->setEnabled(false);
3327 ui->outputFolderLabel->setVisible(false);
3328 ui->outputFolderEdit->setVisible(true);
3329 ui->outputFolderEdit->setText(ui->outputFolderLabel->text());
3330 ui->outputFolderEdit->selectAll();
3331 ui->outputFolderEdit->setFocus();
3333 else if(sender == ui->outputFoldersGoUpLabel)
3335 QTimer::singleShot(0, this, SLOT(goUpFolderContextActionTriggered()));
3339 MUTILS_THROW("Oups, this is not supposed to happen!");
3346 // =========================================================
3347 // Metadata tab slots
3348 // =========================================================
3351 * Edit meta button clicked
3353 void MainWindow::editMetaButtonClicked(void)
3357 const QModelIndex index = ui->metaDataView->currentIndex();
3361 m_metaInfoModel->editItem(index, this);
3363 if(index.row() == 4)
3365 m_settings->metaInfoPosition(m_metaData->position());
3371 * Reset meta button clicked
3373 void MainWindow::clearMetaButtonClicked(void)
3376 m_metaInfoModel->clearData();
3380 * Meta tags enabled changed
3382 void MainWindow::metaTagsEnabledChanged(void)
3384 m_settings->writeMetaTags(ui->writeMetaDataCheckBox->isChecked());
3388 * Playlist enabled changed
3390 void MainWindow::playlistEnabledChanged(void)
3392 m_settings->createPlaylist(ui->generatePlaylistCheckBox->isChecked());
3395 // =========================================================
3396 // Compression tab slots
3397 // =========================================================
3402 void MainWindow::updateEncoder(int id)
3404 /*qWarning("\nupdateEncoder(%d)", id);*/
3406 m_settings->compressionEncoder(id);
3407 const AbstractEncoderInfo *info = EncoderRegistry::getEncoderInfo(id);
3409 //Update UI controls
3410 ui->radioButtonModeQuality ->setEnabled(info->isModeSupported(SettingsModel::VBRMode));
3411 ui->radioButtonModeAverageBitrate->setEnabled(info->isModeSupported(SettingsModel::ABRMode));
3412 ui->radioButtonConstBitrate ->setEnabled(info->isModeSupported(SettingsModel::CBRMode));
3414 //Initialize checkbox state
3415 if(ui->radioButtonModeQuality->isEnabled()) ui->radioButtonModeQuality->setChecked(true);
3416 else if(ui->radioButtonModeAverageBitrate->isEnabled()) ui->radioButtonModeAverageBitrate->setChecked(true);
3417 else if(ui->radioButtonConstBitrate->isEnabled()) ui->radioButtonConstBitrate->setChecked(true);
3418 else MUTILS_THROW("It appears that the encoder does not support *any* RC mode!");
3420 //Apply current RC mode
3421 const int currentRCMode = EncoderRegistry::loadEncoderMode(m_settings, id);
3422 switch(currentRCMode)
3424 case SettingsModel::VBRMode: if(ui->radioButtonModeQuality->isEnabled()) ui->radioButtonModeQuality->setChecked(true); break;
3425 case SettingsModel::ABRMode: if(ui->radioButtonModeAverageBitrate->isEnabled()) ui->radioButtonModeAverageBitrate->setChecked(true); break;
3426 case SettingsModel::CBRMode: if(ui->radioButtonConstBitrate->isEnabled()) ui->radioButtonConstBitrate->setChecked(true); break;
3427 default: MUTILS_THROW("updateEncoder(): Unknown rc-mode encountered!");
3430 //Display encoder description
3431 if(const char* description = info->description())
3433 ui->labelEncoderInfo->setVisible(true);
3434 ui->labelEncoderInfo->setText(tr("Current Encoder: %1").arg(QString::fromUtf8(description)));
3438 ui->labelEncoderInfo->setVisible(false);
3442 updateRCMode(m_modeButtonGroup->checkedId());
3446 * Update rate-control mode
3448 void MainWindow::updateRCMode(int id)
3450 /*qWarning("updateRCMode(%d)", id);*/
3453 const int currentEncoder = m_encoderButtonGroup->checkedId();
3454 EncoderRegistry::saveEncoderMode(m_settings, currentEncoder, id);
3456 //Fetch encoder info
3457 const AbstractEncoderInfo *info = EncoderRegistry::getEncoderInfo(currentEncoder);
3458 const int valueCount = info->valueCount(id);
3461 if(!info->isModeSupported(id))
3463 qWarning("Attempting to use an unsupported RC mode (%d) with current encoder (%d)!", id, currentEncoder);
3464 ui->labelBitrate->setText("(ERROR)");
3468 //Update slider min/max values
3471 WITH_BLOCKED_SIGNALS(ui->sliderBitrate, setEnabled, true);
3472 WITH_BLOCKED_SIGNALS(ui->sliderBitrate, setMinimum, 0);
3473 WITH_BLOCKED_SIGNALS(ui->sliderBitrate, setMaximum, valueCount-1);
3477 WITH_BLOCKED_SIGNALS(ui->sliderBitrate, setEnabled, false);
3478 WITH_BLOCKED_SIGNALS(ui->sliderBitrate, setMinimum, 0);
3479 WITH_BLOCKED_SIGNALS(ui->sliderBitrate, setMaximum, 2);
3482 //Now update bitrate/quality value!
3485 const int currentValue = EncoderRegistry::loadEncoderValue(m_settings, currentEncoder, id);
3486 ui->sliderBitrate->setValue(qBound(0, currentValue, valueCount-1));
3487 updateBitrate(qBound(0, currentValue, valueCount-1));
3491 ui->sliderBitrate->setValue(1);
3499 void MainWindow::updateBitrate(int value)
3501 /*qWarning("updateBitrate(%d)", value);*/
3503 //Load current encoder and RC mode
3504 const int currentEncoder = m_encoderButtonGroup->checkedId();
3505 const int currentRCMode = m_modeButtonGroup->checkedId();
3507 //Fetch encoder info
3508 const AbstractEncoderInfo *info = EncoderRegistry::getEncoderInfo(currentEncoder);
3509 const int valueCount = info->valueCount(currentRCMode);
3512 if(!info->isModeSupported(currentRCMode))
3514 qWarning("Attempting to use an unsupported RC mode (%d) with current encoder (%d)!", currentRCMode, currentEncoder);
3515 ui->labelBitrate->setText("(ERROR)");
3519 //Store new bitrate value
3522 EncoderRegistry::saveEncoderValue(m_settings, currentEncoder, currentRCMode, qBound(0, value, valueCount-1));
3525 //Update bitrate value
3526 const int displayValue = (valueCount > 0) ? info->valueAt(currentRCMode, qBound(0, value, valueCount-1)) : INT_MAX;
3527 switch(info->valueType(currentRCMode))
3529 case AbstractEncoderInfo::TYPE_BITRATE:
3530 ui->labelBitrate->setText(QString("%1 kbps").arg(QString::number(displayValue)));
3532 case AbstractEncoderInfo::TYPE_APPROX_BITRATE:
3533 ui->labelBitrate->setText(QString("≈ %1 kbps").arg(QString::number(displayValue)));
3535 case AbstractEncoderInfo::TYPE_QUALITY_LEVEL_INT:
3536 ui->labelBitrate->setText(tr("Quality Level %1").arg(QString::number(displayValue)));
3538 case AbstractEncoderInfo::TYPE_QUALITY_LEVEL_FLT:
3539 ui->labelBitrate->setText(tr("Quality Level %1").arg(QString().sprintf("%.2f", double(displayValue)/100.0)));
3541 case AbstractEncoderInfo::TYPE_COMPRESSION_LEVEL:
3542 ui->labelBitrate->setText(tr("Compression %1").arg(QString::number(displayValue)));
3544 case AbstractEncoderInfo::TYPE_UNCOMPRESSED:
3545 ui->labelBitrate->setText(tr("Uncompressed"));
3548 MUTILS_THROW("Unknown display value type encountered!");
3554 * Event for compression tab occurred
3556 void MainWindow::compressionTabEventOccurred(QWidget *sender, QEvent *event)
3558 static const QUrl helpUrl("http://lamexp.sourceforge.net/doc/FAQ.html#054010d9");
3560 if((sender == ui->labelCompressionHelp) && (event->type() == QEvent::MouseButtonPress))
3562 QDesktopServices::openUrl(helpUrl);
3564 else if((sender == ui->labelResetEncoders) && (event->type() == QEvent::MouseButtonPress))
3566 PLAY_SOUND_OPTIONAL("blast", true);
3567 EncoderRegistry::resetAllEncoders(m_settings);
3568 m_settings->compressionEncoder(SettingsModel::MP3Encoder);
3569 ui->radioButtonEncoderMP3->setChecked(true);
3570 QTimer::singleShot(0, this, SLOT(updateEncoder()));
3574 // =========================================================
3575 // Advanced option slots
3576 // =========================================================
3579 * Lame algorithm quality changed
3581 void MainWindow::updateLameAlgoQuality(int value)
3588 text = tr("Best Quality (Slow)");
3591 text = tr("High Quality (Recommended)");
3594 text = tr("Acceptable Quality (Fast)");
3597 text = tr("Poor Quality (Very Fast)");
3603 m_settings->lameAlgoQuality(value);
3604 ui->labelLameAlgoQuality->setText(text);
3607 bool warning = (value == 0), notice = (value == 3);
3608 ui->labelLameAlgoQualityWarning->setVisible(warning);
3609 ui->labelLameAlgoQualityWarningIcon->setVisible(warning);
3610 ui->labelLameAlgoQualityNotice->setVisible(notice);
3611 ui->labelLameAlgoQualityNoticeIcon->setVisible(notice);
3612 ui->labelLameAlgoQualitySpacer->setVisible(warning || notice);
3616 * Bitrate management endabled/disabled
3618 void MainWindow::bitrateManagementEnabledChanged(bool checked)
3620 m_settings->bitrateManagementEnabled(checked);
3624 * Minimum bitrate has changed
3626 void MainWindow::bitrateManagementMinChanged(int value)
3628 if(value > ui->spinBoxBitrateManagementMax->value())
3630 ui->spinBoxBitrateManagementMin->setValue(ui->spinBoxBitrateManagementMax->value());
3631 m_settings->bitrateManagementMinRate(ui->spinBoxBitrateManagementMax->value());
3635 m_settings->bitrateManagementMinRate(value);
3640 * Maximum bitrate has changed
3642 void MainWindow::bitrateManagementMaxChanged(int value)
3644 if(value < ui->spinBoxBitrateManagementMin->value())
3646 ui->spinBoxBitrateManagementMax->setValue(ui->spinBoxBitrateManagementMin->value());
3647 m_settings->bitrateManagementMaxRate(ui->spinBoxBitrateManagementMin->value());
3651 m_settings->bitrateManagementMaxRate(value);
3656 * Channel mode has changed
3658 void MainWindow::channelModeChanged(int value)
3660 if(value >= 0) m_settings->lameChannelMode(value);
3664 * Sampling rate has changed
3666 void MainWindow::samplingRateChanged(int value)
3668 if(value >= 0) m_settings->samplingRate(value);
3672 * Nero AAC 2-Pass mode changed
3674 void MainWindow::neroAAC2PassChanged(bool checked)
3676 m_settings->neroAACEnable2Pass(checked);
3680 * Nero AAC profile mode changed
3682 void MainWindow::neroAACProfileChanged(int value)
3684 if(value >= 0) m_settings->aacEncProfile(value);
3688 * Aften audio coding mode changed
3690 void MainWindow::aftenCodingModeChanged(int value)
3692 if(value >= 0) m_settings->aftenAudioCodingMode(value);
3696 * Aften DRC mode changed
3698 void MainWindow::aftenDRCModeChanged(int value)
3700 if(value >= 0) m_settings->aftenDynamicRangeCompression(value);
3704 * Aften exponent search size changed
3706 void MainWindow::aftenSearchSizeChanged(int value)
3708 if(value >= 0) m_settings->aftenExponentSearchSize(value);
3712 * Aften fast bit allocation changed
3714 void MainWindow::aftenFastAllocationChanged(bool checked)
3716 m_settings->aftenFastBitAllocation(checked);
3721 * Opus encoder settings changed
3723 void MainWindow::opusSettingsChanged(void)
3725 m_settings->opusFramesize(ui->comboBoxOpusFramesize->currentIndex());
3726 m_settings->opusComplexity(ui->spinBoxOpusComplexity->value());
3727 m_settings->opusDisableResample(ui->checkBoxOpusDisableResample->isChecked());
3731 * Normalization filter enabled changed
3733 void MainWindow::normalizationEnabledChanged(bool checked)
3735 m_settings->normalizationFilterEnabled(checked);
3739 * Normalization max. volume changed
3741 void MainWindow::normalizationMaxVolumeChanged(double value)
3743 m_settings->normalizationFilterMaxVolume(static_cast<int>(value * 100.0));
3747 * Normalization equalization mode changed
3749 void MainWindow::normalizationModeChanged(int mode)
3751 m_settings->normalizationFilterEQMode(mode);
3755 * Tone adjustment has changed (Bass)
3757 void MainWindow::toneAdjustBassChanged(double value)
3759 m_settings->toneAdjustBass(static_cast<int>(value * 100.0));
3760 ui->spinBoxToneAdjustBass->setPrefix((value > 0) ? "+" : QString());
3764 * Tone adjustment has changed (Treble)
3766 void MainWindow::toneAdjustTrebleChanged(double value)
3768 m_settings->toneAdjustTreble(static_cast<int>(value * 100.0));
3769 ui->spinBoxToneAdjustTreble->setPrefix((value > 0) ? "+" : QString());
3773 * Tone adjustment has been reset
3775 void MainWindow::toneAdjustTrebleReset(void)
3777 ui->spinBoxToneAdjustBass->setValue(m_settings->toneAdjustBassDefault());
3778 ui->spinBoxToneAdjustTreble->setValue(m_settings->toneAdjustTrebleDefault());
3779 toneAdjustBassChanged(ui->spinBoxToneAdjustBass->value());
3780 toneAdjustTrebleChanged(ui->spinBoxToneAdjustTreble->value());
3784 * Custom encoder parameters changed
3786 void MainWindow::customParamsChanged(void)
3788 ui->lineEditCustomParamLAME->setText(ui->lineEditCustomParamLAME->text().simplified());
3789 ui->lineEditCustomParamOggEnc->setText(ui->lineEditCustomParamOggEnc->text().simplified());
3790 ui->lineEditCustomParamNeroAAC->setText(ui->lineEditCustomParamNeroAAC->text().simplified());
3791 ui->lineEditCustomParamFLAC->setText(ui->lineEditCustomParamFLAC->text().simplified());
3792 ui->lineEditCustomParamAften->setText(ui->lineEditCustomParamAften->text().simplified());
3793 ui->lineEditCustomParamOpus->setText(ui->lineEditCustomParamOpus->text().simplified());
3795 bool customParamsUsed = false;
3796 if(!ui->lineEditCustomParamLAME->text().isEmpty()) customParamsUsed = true;
3797 if(!ui->lineEditCustomParamOggEnc->text().isEmpty()) customParamsUsed = true;
3798 if(!ui->lineEditCustomParamNeroAAC->text().isEmpty()) customParamsUsed = true;
3799 if(!ui->lineEditCustomParamFLAC->text().isEmpty()) customParamsUsed = true;
3800 if(!ui->lineEditCustomParamAften->text().isEmpty()) customParamsUsed = true;
3801 if(!ui->lineEditCustomParamOpus->text().isEmpty()) customParamsUsed = true;
3803 ui->labelCustomParamsIcon->setVisible(customParamsUsed);
3804 ui->labelCustomParamsText->setVisible(customParamsUsed);
3805 ui->labelCustomParamsSpacer->setVisible(customParamsUsed);
3807 EncoderRegistry::saveEncoderCustomParams(m_settings, SettingsModel::MP3Encoder, ui->lineEditCustomParamLAME->text());
3808 EncoderRegistry::saveEncoderCustomParams(m_settings, SettingsModel::VorbisEncoder, ui->lineEditCustomParamOggEnc->text());
3809 EncoderRegistry::saveEncoderCustomParams(m_settings, SettingsModel::AACEncoder, ui->lineEditCustomParamNeroAAC->text());
3810 EncoderRegistry::saveEncoderCustomParams(m_settings, SettingsModel::FLACEncoder, ui->lineEditCustomParamFLAC->text());
3811 EncoderRegistry::saveEncoderCustomParams(m_settings, SettingsModel::AC3Encoder, ui->lineEditCustomParamAften->text());
3812 EncoderRegistry::saveEncoderCustomParams(m_settings, SettingsModel::OpusEncoder, ui->lineEditCustomParamOpus->text());
3816 * Rename output files enabled changed
3818 void MainWindow::renameOutputEnabledChanged(bool checked)
3820 m_settings->renameOutputFilesEnabled(checked);
3824 * Rename output files patterm changed
3826 void MainWindow::renameOutputPatternChanged(void)
3828 QString temp = ui->lineEditRenamePattern->text().simplified();
3829 ui->lineEditRenamePattern->setText(temp.isEmpty() ? m_settings->renameOutputFilesPatternDefault() : temp);
3830 m_settings->renameOutputFilesPattern(ui->lineEditRenamePattern->text());
3834 * Rename output files patterm changed
3836 void MainWindow::renameOutputPatternChanged(const QString &text, bool silent)
3838 QString pattern(text.simplified());
3840 pattern.replace("<BaseName>", "The_White_Stripes_-_Fell_In_Love_With_A_Girl", Qt::CaseInsensitive);
3841 pattern.replace("<TrackNo>", "04", Qt::CaseInsensitive);
3842 pattern.replace("<Title>", "Fell In Love With A Girl", Qt::CaseInsensitive);
3843 pattern.replace("<Artist>", "The White Stripes", Qt::CaseInsensitive);
3844 pattern.replace("<Album>", "White Blood Cells", Qt::CaseInsensitive);
3845 pattern.replace("<Year>", "2001", Qt::CaseInsensitive);
3846 pattern.replace("<Comment>", "Encoded by LameXP", Qt::CaseInsensitive);
3848 const QString patternClean = lamexp_clean_filename(pattern);
3850 if(pattern.compare(patternClean))
3852 if(ui->lineEditRenamePattern->palette().color(QPalette::Text) != Qt::red)
3854 if(!silent) lamexp_beep(lamexp_beep_error);
3855 SET_TEXT_COLOR(ui->lineEditRenamePattern, Qt::red);
3860 if(ui->lineEditRenamePattern->palette() != QPalette())
3862 if(!silent) lamexp_beep(lamexp_beep_info);
3863 ui->lineEditRenamePattern->setPalette(QPalette());
3867 ui->labelRanameExample->setText(patternClean);
3871 * Show list of rename macros
3873 void MainWindow::showRenameMacros(const QString &text)
3875 if(text.compare("reset", Qt::CaseInsensitive) == 0)
3877 ui->lineEditRenamePattern->setText(m_settings->renameOutputFilesPatternDefault());
3881 const QString format = QString("<tr><td><tt><%1></tt></td><td> </td><td>%2</td></tr>");
3883 QString message = QString("<table>");
3884 message += QString(format).arg("BaseName", tr("File name without extension"));
3885 message += QString(format).arg("TrackNo", tr("Track number with leading zero"));
3886 message += QString(format).arg("Title", tr("Track title"));
3887 message += QString(format).arg("Artist", tr("Artist name"));
3888 message += QString(format).arg("Album", tr("Album name"));
3889 message += QString(format).arg("Year", tr("Year with (at least) four digits"));
3890 message += QString(format).arg("Comment", tr("Comment"));
3891 message += "</table><br><br>";
3892 message += QString("%1<br>").arg(tr("Characters forbidden in file names:"));
3893 message += "<b><tt>\\ / : * ? < > |<br>";
3895 QMessageBox::information(this, tr("Rename Macros"), message, tr("Discard"));
3898 void MainWindow::forceStereoDownmixEnabledChanged(bool checked)
3900 m_settings->forceStereoDownmix(checked);
3904 * Maximum number of instances changed
3906 void MainWindow::updateMaximumInstances(int value)
3908 ui->labelMaxInstances->setText(tr("%n Instance(s)", "", value));
3909 m_settings->maximumInstances(ui->checkBoxAutoDetectInstances->isChecked() ? NULL : value);
3913 * Auto-detect number of instances
3915 void MainWindow::autoDetectInstancesChanged(bool checked)
3917 m_settings->maximumInstances(checked ? NULL : ui->sliderMaxInstances->value());
3921 * Browse for custom TEMP folder button clicked
3923 void MainWindow::browseCustomTempFolderButtonClicked(void)
3925 QString newTempFolder;
3927 if(lamexp_themes_enabled())
3929 newTempFolder = QFileDialog::getExistingDirectory(this, QString(), m_settings->customTempPath());
3933 QFileDialog dialog(this);
3934 dialog.setFileMode(QFileDialog::DirectoryOnly);
3935 dialog.setDirectory(m_settings->customTempPath());
3938 newTempFolder = dialog.selectedFiles().first();
3942 if(!newTempFolder.isEmpty())
3944 QFile writeTest(QString("%1/~%2.tmp").arg(newTempFolder, MUtils::rand_str()));
3945 if(writeTest.open(QIODevice::ReadWrite))
3948 ui->lineEditCustomTempFolder->setText(QDir::toNativeSeparators(newTempFolder));
3952 QMessageBox::warning(this, tr("Access Denied"), tr("Cannot write to the selected directory. Please choose another directory!"));
3958 * Custom TEMP folder changed
3960 void MainWindow::customTempFolderChanged(const QString &text)
3962 m_settings->customTempPath(QDir::fromNativeSeparators(text));
3966 * Use custom TEMP folder option changed
3968 void MainWindow::useCustomTempFolderChanged(bool checked)
3970 m_settings->customTempPathEnabled(!checked);
3974 * Help for custom parameters was requested
3976 void MainWindow::customParamsHelpRequested(QWidget *obj, QEvent *event)
3978 if(event->type() != QEvent::MouseButtonRelease)
3983 if(QMouseEvent *mouseEvent = dynamic_cast<QMouseEvent*>(event))
3985 QPoint pos = mouseEvent->pos();
3986 if(!(pos.x() <= obj->width() && pos.y() <= obj->height() && pos.x() >= 0 && pos.y() >= 0 && mouseEvent->button() != Qt::MidButton))
3992 if(obj == ui->helpCustomParamLAME) showCustomParamsHelpScreen("lame.exe", "--longhelp");
3993 else if(obj == ui->helpCustomParamOggEnc) showCustomParamsHelpScreen("oggenc2.exe", "--help");
3994 else if(obj == ui->helpCustomParamNeroAAC)
3996 switch(EncoderRegistry::getAacEncoder())
3998 case SettingsModel::AAC_ENCODER_QAAC: showCustomParamsHelpScreen("qaac.exe", "--help"); break;
3999 case SettingsModel::AAC_ENCODER_FHG : showCustomParamsHelpScreen("fhgaacenc.exe", ""); break;
4000 case SettingsModel::AAC_ENCODER_NERO: showCustomParamsHelpScreen("neroAacEnc.exe", "-help"); break;
4001 default: lamexp_beep(lamexp_beep_error); break;
4004 else if(obj == ui->helpCustomParamFLAC) showCustomParamsHelpScreen("flac.exe", "--help");
4005 else if(obj == ui->helpCustomParamAften) showCustomParamsHelpScreen("aften.exe", "-h");
4006 else if(obj == ui->helpCustomParamOpus) showCustomParamsHelpScreen("opusenc.exe", "--help");
4007 else lamexp_beep(lamexp_beep_error);
4011 * Show help for custom parameters
4013 void MainWindow::showCustomParamsHelpScreen(const QString &toolName, const QString &command)
4015 const QString binary = lamexp_lookup_tool(toolName);
4016 if(binary.isEmpty())
4018 lamexp_beep(lamexp_beep_error);
4019 qWarning("customParamsHelpRequested: Binary could not be found!");
4024 MUtils::init_process(process, QFileInfo(binary).absolutePath());
4026 process.start(binary, command.isEmpty() ? QStringList() : QStringList() << command);
4028 qApp->setOverrideCursor(QCursor(Qt::WaitCursor));
4030 if(process.waitForStarted(15000))
4032 qApp->processEvents();
4033 process.waitForFinished(15000);
4036 if(process.state() != QProcess::NotRunning)
4039 process.waitForFinished(-1);
4042 qApp->restoreOverrideCursor();
4043 QStringList output; bool spaceFlag = true;
4045 while(process.canReadLine())
4047 QString temp = QString::fromUtf8(process.readLine());
4048 TRIM_STRING_RIGHT(temp);
4051 if(!spaceFlag) { output << temp; spaceFlag = true; }
4055 output << temp; spaceFlag = false;
4059 if(output.count() < 1)
4061 qWarning("Empty output, cannot show help screen!");
4062 lamexp_beep(lamexp_beep_error);
4065 LogViewDialog *dialog = new LogViewDialog(this);
4066 TEMP_HIDE_DROPBOX( dialog->exec(output); );
4067 MUTILS_DELETE(dialog);
4070 void MainWindow::overwriteModeChanged(int id)
4072 if((id == SettingsModel::Overwrite_Replaces) && (m_settings->overwriteMode() != SettingsModel::Overwrite_Replaces))
4074 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)
4076 ui->radioButtonOverwriteModeKeepBoth->setChecked(m_settings->overwriteMode() == SettingsModel::Overwrite_KeepBoth);
4077 ui->radioButtonOverwriteModeSkipFile->setChecked(m_settings->overwriteMode() == SettingsModel::Overwrite_SkipFile);
4082 m_settings->overwriteMode(id);
4086 * Reset all advanced options to their defaults
4088 void MainWindow::resetAdvancedOptionsButtonClicked(void)
4090 PLAY_SOUND_OPTIONAL("blast", true);
4092 ui->sliderLameAlgoQuality->setValue(m_settings->lameAlgoQualityDefault());
4093 ui->spinBoxBitrateManagementMin->setValue(m_settings->bitrateManagementMinRateDefault());
4094 ui->spinBoxBitrateManagementMax->setValue(m_settings->bitrateManagementMaxRateDefault());
4095 ui->spinBoxNormalizationFilter->setValue(static_cast<double>(m_settings->normalizationFilterMaxVolumeDefault()) / 100.0);
4096 ui->spinBoxToneAdjustBass->setValue(static_cast<double>(m_settings->toneAdjustBassDefault()) / 100.0);
4097 ui->spinBoxToneAdjustTreble->setValue(static_cast<double>(m_settings->toneAdjustTrebleDefault()) / 100.0);
4098 ui->spinBoxAftenSearchSize->setValue(m_settings->aftenExponentSearchSizeDefault());
4099 ui->spinBoxOpusComplexity->setValue(m_settings->opusComplexityDefault());
4100 ui->comboBoxMP3ChannelMode->setCurrentIndex(m_settings->lameChannelModeDefault());
4101 ui->comboBoxSamplingRate->setCurrentIndex(m_settings->samplingRateDefault());
4102 ui->comboBoxAACProfile->setCurrentIndex(m_settings->aacEncProfileDefault());
4103 ui->comboBoxAftenCodingMode->setCurrentIndex(m_settings->aftenAudioCodingModeDefault());
4104 ui->comboBoxAftenDRCMode->setCurrentIndex(m_settings->aftenDynamicRangeCompressionDefault());
4105 ui->comboBoxNormalizationMode->setCurrentIndex(m_settings->normalizationFilterEQModeDefault());
4106 ui->comboBoxOpusFramesize->setCurrentIndex(m_settings->opusFramesizeDefault());
4108 SET_CHECKBOX_STATE(ui->checkBoxBitrateManagement, m_settings->bitrateManagementEnabledDefault());
4109 SET_CHECKBOX_STATE(ui->checkBoxNeroAAC2PassMode, m_settings->neroAACEnable2PassDefault());
4110 SET_CHECKBOX_STATE(ui->checkBoxNormalizationFilter, m_settings->normalizationFilterEnabledDefault());
4111 SET_CHECKBOX_STATE(ui->checkBoxAutoDetectInstances, (m_settings->maximumInstancesDefault() < 1));
4112 SET_CHECKBOX_STATE(ui->checkBoxUseSystemTempFolder, !m_settings->customTempPathEnabledDefault());
4113 SET_CHECKBOX_STATE(ui->checkBoxAftenFastAllocation, m_settings->aftenFastBitAllocationDefault());
4114 SET_CHECKBOX_STATE(ui->checkBoxRenameOutput, m_settings->renameOutputFilesEnabledDefault());
4115 SET_CHECKBOX_STATE(ui->checkBoxForceStereoDownmix, m_settings->forceStereoDownmixDefault());
4116 SET_CHECKBOX_STATE(ui->checkBoxOpusDisableResample, m_settings->opusDisableResampleDefault());
4118 ui->lineEditCustomParamLAME ->setText(m_settings->customParametersLAMEDefault());
4119 ui->lineEditCustomParamOggEnc ->setText(m_settings->customParametersOggEncDefault());
4120 ui->lineEditCustomParamNeroAAC->setText(m_settings->customParametersAacEncDefault());
4121 ui->lineEditCustomParamFLAC ->setText(m_settings->customParametersFLACDefault());
4122 ui->lineEditCustomParamOpus ->setText(m_settings->customParametersOpusEncDefault());
4123 ui->lineEditCustomTempFolder ->setText(QDir::toNativeSeparators(m_settings->customTempPathDefault()));
4124 ui->lineEditRenamePattern ->setText(m_settings->renameOutputFilesPatternDefault());
4126 if(m_settings->overwriteModeDefault() == SettingsModel::Overwrite_KeepBoth) ui->radioButtonOverwriteModeKeepBoth->click();
4127 if(m_settings->overwriteModeDefault() == SettingsModel::Overwrite_SkipFile) ui->radioButtonOverwriteModeSkipFile->click();
4128 if(m_settings->overwriteModeDefault() == SettingsModel::Overwrite_Replaces) ui->radioButtonOverwriteModeReplaces->click();
4130 customParamsChanged();
4131 ui->scrollArea->verticalScrollBar()->setValue(0);
4134 // =========================================================
4135 // Multi-instance handling slots
4136 // =========================================================
4139 * Other instance detected
4141 void MainWindow::notifyOtherInstance(void)
4143 if(!(BANNER_VISIBLE))
4145 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);
4151 * Add file from another instance
4153 void MainWindow::addFileDelayed(const QString &filePath, bool tryASAP)
4155 if(tryASAP && !m_delayedFileTimer->isActive())
4157 qDebug("Received file: %s", MUTILS_UTF8(filePath));
4158 m_delayedFileList->append(filePath);
4159 QTimer::singleShot(0, this, SLOT(handleDelayedFiles()));
4162 m_delayedFileTimer->stop();
4163 qDebug("Received file: %s", MUTILS_UTF8(filePath));
4164 m_delayedFileList->append(filePath);
4165 m_delayedFileTimer->start(5000);
4169 * Add files from another instance
4171 void MainWindow::addFilesDelayed(const QStringList &filePaths, bool tryASAP)
4173 if(tryASAP && (!m_delayedFileTimer->isActive()))
4175 qDebug("Received %d file(s).", filePaths.count());
4176 m_delayedFileList->append(filePaths);
4177 QTimer::singleShot(0, this, SLOT(handleDelayedFiles()));
4181 m_delayedFileTimer->stop();
4182 qDebug("Received %d file(s).", filePaths.count());
4183 m_delayedFileList->append(filePaths);
4184 m_delayedFileTimer->start(5000);
4189 * Add folder from another instance
4191 void MainWindow::addFolderDelayed(const QString &folderPath, bool recursive)
4193 if(!(BANNER_VISIBLE))
4195 addFolder(folderPath, recursive, true);
4199 // =========================================================
4201 // =========================================================
4204 * Restore the override cursor
4206 void MainWindow::restoreCursor(void)
4208 QApplication::restoreOverrideCursor();