1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2013 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.
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License along
16 // with this program; if not, write to the Free Software Foundation, Inc.,
17 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
22 #include "Dialog_MainWindow.h"
25 #include "../tmp/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_FileAnalyzer_ST.h"
39 #include "Thread_MessageHandler.h"
40 #include "Model_MetaInfo.h"
41 #include "Model_Settings.h"
42 #include "Model_FileList.h"
43 #include "Model_FileSystem.h"
44 #include "WinSevenTaskbar.h"
45 #include "Registry_Decoder.h"
46 #include "ShellIntegration.h"
47 #include "CustomEventFilter.h"
50 #include <QMessageBox>
52 #include <QDesktopWidget>
54 #include <QFileDialog>
55 #include <QInputDialog>
56 #include <QFileSystemModel>
57 #include <QDesktopServices>
59 #include <QPlastiqueStyle>
60 #include <QCleanlooksStyle>
61 #include <QWindowsVistaStyle>
62 #include <QWindowsStyle>
64 #include <QDragEnterEvent>
68 #include <QProcessEnvironment>
69 #include <QCryptographicHash>
70 #include <QTranslator>
78 ////////////////////////////////////////////////////////////
80 ////////////////////////////////////////////////////////////
82 #define ABORT_IF_BUSY do \
84 if(m_banner->isVisible() || m_delayedFileTimer->isActive()) \
86 MessageBeep(MB_ICONEXCLAMATION); \
92 #define SET_TEXT_COLOR(WIDGET, COLOR) do \
94 QPalette _palette = WIDGET->palette(); \
95 _palette.setColor(QPalette::WindowText, (COLOR)); \
96 _palette.setColor(QPalette::Text, (COLOR)); \
97 WIDGET->setPalette(_palette); \
101 #define SET_FONT_BOLD(WIDGET,BOLD) do \
103 QFont _font = WIDGET->font(); \
104 _font.setBold(BOLD); \
105 WIDGET->setFont(_font); \
109 #define TEMP_HIDE_DROPBOX(CMD) do \
111 bool _dropBoxVisible = m_dropBox->isVisible(); \
112 if(_dropBoxVisible) m_dropBox->hide(); \
113 do { CMD } while(0); \
114 if(_dropBoxVisible) m_dropBox->show(); \
118 #define SET_MODEL(VIEW, MODEL) do \
120 QItemSelectionModel *_tmp = (VIEW)->selectionModel(); \
121 (VIEW)->setModel(MODEL); \
122 LAMEXP_DELETE(_tmp); \
126 #define SET_CHECKBOX_STATE(CHCKBX, STATE) do \
128 if((CHCKBX)->isChecked() != (STATE)) \
132 if((CHCKBX)->isChecked() != (STATE)) \
134 qWarning("Warning: Failed to set checkbox " #CHCKBX " state!"); \
139 #define TRIM_STRING_RIGHT(STR) do \
141 while((STR.length() > 0) && STR[STR.length()-1].isSpace()) STR.chop(1); \
145 #define MAKE_TRANSPARENT(WIDGET, FLAG) do \
147 QPalette _p = (WIDGET)->palette(); \
148 _p.setColor(QPalette::Background, Qt::transparent); \
149 (WIDGET)->setPalette(FLAG ? _p : QPalette()); \
153 #define LINK(URL) QString("<a href=\"%1\">%2</a>").arg(URL).arg(QString(URL).replace("-", "−"))
154 #define FSLINK(PATH) QString("<a href=\"file:///%1\">%2</a>").arg(PATH).arg(QString(PATH).replace("-", "−"))
155 //#define USE_NATIVE_FILE_DIALOG (lamexp_themes_enabled() || ((QSysInfo::windowsVersion() & QSysInfo::WV_NT_based) < QSysInfo::WV_XP))
156 #define CENTER_CURRENT_OUTPUT_FOLDER_DELAYED QTimer::singleShot(125, this, SLOT(centerOutputFolderModel()))
158 static const DWORD IDM_ABOUTBOX = 0xEFF0;
160 ////////////////////////////////////////////////////////////
162 ////////////////////////////////////////////////////////////
164 MainWindow::MainWindow(FileListModel *fileListModel, AudioFileModel *metaInfo, SettingsModel *settingsModel, QWidget *parent)
167 ui(new Ui::MainWindow),
168 m_fileListModel(fileListModel),
169 m_metaData(metaInfo),
170 m_settings(settingsModel),
171 m_fileSystemModel(NULL),
172 m_neroEncoderAvailable(lamexp_check_tool("neroAacEnc.exe") && lamexp_check_tool("neroAacDec.exe") && lamexp_check_tool("neroAacTag.exe")),
173 m_fhgEncoderAvailable(lamexp_check_tool("fhgaacenc.exe") && lamexp_check_tool("enc_fhgaac.dll") && lamexp_check_tool("nsutil.dll") && lamexp_check_tool("libmp4v2.dll")),
174 m_qaacEncoderAvailable(lamexp_check_tool("qaac.exe") && lamexp_check_tool("libsoxrate.dll")),
176 m_firstTimeShown(true),
177 m_outputFolderViewCentering(false),
178 m_outputFolderViewInitCounter(0)
180 //Init the dialog, from the .ui file
182 setWindowFlags(windowFlags() ^ Qt::WindowMaximizeButtonHint);
184 //Register meta types
185 qRegisterMetaType<AudioFileModel>("AudioFileModel");
187 //Enabled main buttons
188 connect(ui->buttonAbout, SIGNAL(clicked()), this, SLOT(aboutButtonClicked()));
189 connect(ui->buttonStart, SIGNAL(clicked()), this, SLOT(encodeButtonClicked()));
190 connect(ui->buttonQuit, SIGNAL(clicked()), this, SLOT(closeButtonClicked()));
193 ui->tabWidget->setCurrentIndex(0);
194 connect(ui->tabWidget, SIGNAL(currentChanged(int)), this, SLOT(tabPageChanged(int)));
197 if(HMENU hMenu = ::GetSystemMenu(winId(), FALSE))
199 AppendMenuW(hMenu, MF_SEPARATOR, 0, 0);
200 AppendMenuW(hMenu, MF_STRING, IDM_ABOUTBOX, L"About...");
203 //--------------------------------
204 // Setup "Source" tab
205 //--------------------------------
207 ui->sourceFileView->setModel(m_fileListModel);
208 ui->sourceFileView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
209 ui->sourceFileView->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);
210 ui->sourceFileView->setContextMenuPolicy(Qt::CustomContextMenu);
211 ui->sourceFileView->viewport()->installEventFilter(this);
212 m_dropNoteLabel = new QLabel(ui->sourceFileView);
213 m_dropNoteLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
214 SET_FONT_BOLD(m_dropNoteLabel, true);
215 SET_TEXT_COLOR(m_dropNoteLabel, Qt::darkGray);
216 m_sourceFilesContextMenu = new QMenu();
217 m_showDetailsContextAction = m_sourceFilesContextMenu->addAction(QIcon(":/icons/zoom.png"), "N/A");
218 m_previewContextAction = m_sourceFilesContextMenu->addAction(QIcon(":/icons/sound.png"), "N/A");
219 m_findFileContextAction = m_sourceFilesContextMenu->addAction(QIcon(":/icons/folder_go.png"), "N/A");
220 m_sourceFilesContextMenu->addSeparator();
221 m_exportCsvContextAction = m_sourceFilesContextMenu->addAction(QIcon(":/icons/table_save.png"), "N/A");
222 m_importCsvContextAction = m_sourceFilesContextMenu->addAction(QIcon(":/icons/folder_table.png"), "N/A");
223 SET_FONT_BOLD(m_showDetailsContextAction, true);
224 connect(ui->buttonAddFiles, SIGNAL(clicked()), this, SLOT(addFilesButtonClicked()));
225 connect(ui->buttonRemoveFile, SIGNAL(clicked()), this, SLOT(removeFileButtonClicked()));
226 connect(ui->buttonClearFiles, SIGNAL(clicked()), this, SLOT(clearFilesButtonClicked()));
227 connect(ui->buttonFileUp, SIGNAL(clicked()), this, SLOT(fileUpButtonClicked()));
228 connect(ui->buttonFileDown, SIGNAL(clicked()), this, SLOT(fileDownButtonClicked()));
229 connect(ui->buttonShowDetails, SIGNAL(clicked()), this, SLOT(showDetailsButtonClicked()));
230 connect(m_fileListModel, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(sourceModelChanged()));
231 connect(m_fileListModel, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(sourceModelChanged()));
232 connect(m_fileListModel, SIGNAL(modelReset()), this, SLOT(sourceModelChanged()));
233 connect(ui->sourceFileView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(sourceFilesContextMenu(QPoint)));
234 connect(ui->sourceFileView->verticalScrollBar(), SIGNAL(sliderMoved(int)), this, SLOT(sourceFilesScrollbarMoved(int)));
235 connect(ui->sourceFileView->verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(sourceFilesScrollbarMoved(int)));
236 connect(m_showDetailsContextAction, SIGNAL(triggered(bool)), this, SLOT(showDetailsButtonClicked()));
237 connect(m_previewContextAction, SIGNAL(triggered(bool)), this, SLOT(previewContextActionTriggered()));
238 connect(m_findFileContextAction, SIGNAL(triggered(bool)), this, SLOT(findFileContextActionTriggered()));
239 connect(m_exportCsvContextAction, SIGNAL(triggered(bool)), this, SLOT(exportCsvContextActionTriggered()));
240 connect(m_importCsvContextAction, SIGNAL(triggered(bool)), this, SLOT(importCsvContextActionTriggered()));
242 //--------------------------------
243 // Setup "Output" tab
244 //--------------------------------
246 ui->outputFolderView->setHeaderHidden(true);
247 ui->outputFolderView->setAnimated(false);
248 ui->outputFolderView->setMouseTracking(false);
249 ui->outputFolderView->setContextMenuPolicy(Qt::CustomContextMenu);
250 ui->outputFolderView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
252 m_evenFilterOutputFolderMouse = new CustomEventFilter;
253 ui->outputFoldersGoUpLabel->installEventFilter(m_evenFilterOutputFolderMouse);
254 ui->outputFoldersEditorLabel->installEventFilter(m_evenFilterOutputFolderMouse);
255 ui->outputFoldersFovoritesLabel->installEventFilter(m_evenFilterOutputFolderMouse);
256 ui->outputFolderLabel->installEventFilter(m_evenFilterOutputFolderMouse);
258 m_evenFilterOutputFolderView = new CustomEventFilter;
259 ui->outputFolderView->installEventFilter(m_evenFilterOutputFolderView);
261 SET_CHECKBOX_STATE(ui->saveToSourceFolderCheckBox, m_settings->outputToSourceDir());
262 ui->prependRelativePathCheckBox->setChecked(m_settings->prependRelativeSourcePath());
264 connect(ui->outputFolderView, SIGNAL(clicked(QModelIndex)), this, SLOT(outputFolderViewClicked(QModelIndex)));
265 connect(ui->outputFolderView, SIGNAL(activated(QModelIndex)), this, SLOT(outputFolderViewClicked(QModelIndex)));
266 connect(ui->outputFolderView, SIGNAL(pressed(QModelIndex)), this, SLOT(outputFolderViewClicked(QModelIndex)));
267 connect(ui->outputFolderView, SIGNAL(entered(QModelIndex)), this, SLOT(outputFolderViewMoved(QModelIndex)));
268 connect(ui->outputFolderView, SIGNAL(expanded(QModelIndex)), this, SLOT(outputFolderItemExpanded(QModelIndex)));
269 connect(ui->buttonMakeFolder, SIGNAL(clicked()), this, SLOT(makeFolderButtonClicked()));
270 connect(ui->buttonGotoHome, SIGNAL(clicked()), SLOT(gotoHomeFolderButtonClicked()));
271 connect(ui->buttonGotoDesktop, SIGNAL(clicked()), this, SLOT(gotoDesktopButtonClicked()));
272 connect(ui->buttonGotoMusic, SIGNAL(clicked()), this, SLOT(gotoMusicFolderButtonClicked()));
273 connect(ui->saveToSourceFolderCheckBox, SIGNAL(clicked()), this, SLOT(saveToSourceFolderChanged()));
274 connect(ui->prependRelativePathCheckBox, SIGNAL(clicked()), this, SLOT(prependRelativePathChanged()));
275 connect(ui->outputFolderEdit, SIGNAL(editingFinished()), this, SLOT(outputFolderEditFinished()));
276 connect(m_evenFilterOutputFolderMouse, SIGNAL(eventOccurred(QWidget*, QEvent*)), this, SLOT(outputFolderMouseEventOccurred(QWidget*, QEvent*)));
277 connect(m_evenFilterOutputFolderView, SIGNAL(eventOccurred(QWidget*, QEvent*)), this, SLOT(outputFolderViewEventOccurred(QWidget*, QEvent*)));
279 if(m_outputFolderContextMenu = new QMenu())
281 m_showFolderContextAction = m_outputFolderContextMenu->addAction(QIcon(":/icons/zoom.png"), "N/A");
282 m_goUpFolderContextAction = m_outputFolderContextMenu->addAction(QIcon(":/icons/folder_up.png"), "N/A");
283 m_outputFolderContextMenu->addSeparator();
284 m_refreshFolderContextAction = m_outputFolderContextMenu->addAction(QIcon(":/icons/arrow_refresh.png"), "N/A");
285 m_outputFolderContextMenu->setDefaultAction(m_showFolderContextAction);
286 connect(ui->outputFolderView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(outputFolderContextMenu(QPoint)));
287 connect(m_showFolderContextAction, SIGNAL(triggered(bool)), this, SLOT(showFolderContextActionTriggered()));
288 connect(m_refreshFolderContextAction, SIGNAL(triggered(bool)), this, SLOT(refreshFolderContextActionTriggered()));
289 connect(m_goUpFolderContextAction, SIGNAL(triggered(bool)), this, SLOT(goUpFolderContextActionTriggered()));
292 if(m_outputFolderFavoritesMenu = new QMenu())
294 m_addFavoriteFolderAction = m_outputFolderFavoritesMenu->addAction(QIcon(":/icons/add.png"), "N/A");
295 m_outputFolderFavoritesMenu->insertSeparator(m_addFavoriteFolderAction);
296 connect(m_addFavoriteFolderAction, SIGNAL(triggered(bool)), this, SLOT(addFavoriteFolderActionTriggered()));
299 ui->outputFolderEdit->setVisible(false);
300 if(m_outputFolderNoteBox = new QLabel(ui->outputFolderView))
302 m_outputFolderNoteBox->setAutoFillBackground(true);
303 m_outputFolderNoteBox->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
304 m_outputFolderNoteBox->setFrameShape(QFrame::StyledPanel);
305 SET_FONT_BOLD(m_outputFolderNoteBox, true);
306 m_outputFolderNoteBox->hide();
310 outputFolderViewClicked(QModelIndex());
313 //--------------------------------
314 // Setup "Meta Data" tab
315 //--------------------------------
317 m_metaInfoModel = new MetaInfoModel(m_metaData, 6);
318 m_metaInfoModel->clearData();
319 m_metaInfoModel->setData(m_metaInfoModel->index(4, 1), m_settings->metaInfoPosition());
320 ui->metaDataView->setModel(m_metaInfoModel);
321 ui->metaDataView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
322 ui->metaDataView->verticalHeader()->hide();
323 ui->metaDataView->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);
324 SET_CHECKBOX_STATE(ui->writeMetaDataCheckBox, m_settings->writeMetaTags());
325 ui->generatePlaylistCheckBox->setChecked(m_settings->createPlaylist());
326 connect(ui->buttonEditMeta, SIGNAL(clicked()), this, SLOT(editMetaButtonClicked()));
327 connect(ui->buttonClearMeta, SIGNAL(clicked()), this, SLOT(clearMetaButtonClicked()));
328 connect(ui->writeMetaDataCheckBox, SIGNAL(clicked()), this, SLOT(metaTagsEnabledChanged()));
329 connect(ui->generatePlaylistCheckBox, SIGNAL(clicked()), this, SLOT(playlistEnabledChanged()));
331 //--------------------------------
332 //Setup "Compression" tab
333 //--------------------------------
335 m_encoderButtonGroup = new QButtonGroup(this);
336 m_encoderButtonGroup->addButton(ui->radioButtonEncoderMP3, SettingsModel::MP3Encoder);
337 m_encoderButtonGroup->addButton(ui->radioButtonEncoderVorbis, SettingsModel::VorbisEncoder);
338 m_encoderButtonGroup->addButton(ui->radioButtonEncoderAAC, SettingsModel::AACEncoder);
339 m_encoderButtonGroup->addButton(ui->radioButtonEncoderAC3, SettingsModel::AC3Encoder);
340 m_encoderButtonGroup->addButton(ui->radioButtonEncoderFLAC, SettingsModel::FLACEncoder);
341 m_encoderButtonGroup->addButton(ui->radioButtonEncoderOpus, SettingsModel::OpusEncoder);
342 m_encoderButtonGroup->addButton(ui->radioButtonEncoderDCA, SettingsModel::DCAEncoder);
343 m_encoderButtonGroup->addButton(ui->radioButtonEncoderPCM, SettingsModel::PCMEncoder);
345 m_modeButtonGroup = new QButtonGroup(this);
346 m_modeButtonGroup->addButton(ui->radioButtonModeQuality, SettingsModel::VBRMode);
347 m_modeButtonGroup->addButton(ui->radioButtonModeAverageBitrate, SettingsModel::ABRMode);
348 m_modeButtonGroup->addButton(ui->radioButtonConstBitrate, SettingsModel::CBRMode);
350 ui->radioButtonEncoderAAC->setEnabled(m_neroEncoderAvailable || m_fhgEncoderAvailable || m_qaacEncoderAvailable);
351 ui->radioButtonEncoderMP3->setChecked(m_settings->compressionEncoder() == SettingsModel::MP3Encoder);
352 ui->radioButtonEncoderVorbis->setChecked(m_settings->compressionEncoder() == SettingsModel::VorbisEncoder);
353 ui->radioButtonEncoderAAC->setChecked((m_settings->compressionEncoder() == SettingsModel::AACEncoder) && (m_neroEncoderAvailable || m_fhgEncoderAvailable || m_qaacEncoderAvailable));
354 ui->radioButtonEncoderAC3->setChecked(m_settings->compressionEncoder() == SettingsModel::AC3Encoder);
355 ui->radioButtonEncoderFLAC->setChecked(m_settings->compressionEncoder() == SettingsModel::FLACEncoder);
356 ui->radioButtonEncoderOpus->setChecked(m_settings->compressionEncoder() == SettingsModel::OpusEncoder);
357 ui->radioButtonEncoderDCA->setChecked(m_settings->compressionEncoder() == SettingsModel::DCAEncoder);
358 ui->radioButtonEncoderPCM->setChecked(m_settings->compressionEncoder() == SettingsModel::PCMEncoder);
359 ui->radioButtonModeQuality->setChecked(m_settings->compressionRCMode() == SettingsModel::VBRMode);
360 ui->radioButtonModeAverageBitrate->setChecked(m_settings->compressionRCMode() == SettingsModel::ABRMode);
361 ui->radioButtonConstBitrate->setChecked(m_settings->compressionRCMode() == SettingsModel::CBRMode);
362 ui->sliderBitrate->setValue(m_settings->compressionBitrate());
364 m_evenFilterCompressionTab = new CustomEventFilter();
365 ui->labelCompressionHelp->installEventFilter(m_evenFilterCompressionTab);
367 connect(m_encoderButtonGroup, SIGNAL(buttonClicked(int)), this, SLOT(updateEncoder(int)));
368 connect(m_modeButtonGroup, SIGNAL(buttonClicked(int)), this, SLOT(updateRCMode(int)));
369 connect(m_evenFilterCompressionTab, SIGNAL(eventOccurred(QWidget*, QEvent*)), this, SLOT(compressionTabEventOccurred(QWidget*, QEvent*)));
370 connect(ui->sliderBitrate, SIGNAL(valueChanged(int)), this, SLOT(updateBitrate(int)));
372 updateEncoder(m_encoderButtonGroup->checkedId());
374 //--------------------------------
375 //Setup "Advanced Options" tab
376 //--------------------------------
378 ui->sliderLameAlgoQuality->setValue(m_settings->lameAlgoQuality());
379 if(m_settings->maximumInstances() > 0) ui->sliderMaxInstances->setValue(m_settings->maximumInstances());
381 ui->spinBoxBitrateManagementMin->setValue(m_settings->bitrateManagementMinRate());
382 ui->spinBoxBitrateManagementMax->setValue(m_settings->bitrateManagementMaxRate());
383 ui->spinBoxNormalizationFilter->setValue(static_cast<double>(m_settings->normalizationFilterMaxVolume()) / 100.0);
384 ui->spinBoxToneAdjustBass->setValue(static_cast<double>(m_settings->toneAdjustBass()) / 100.0);
385 ui->spinBoxToneAdjustTreble->setValue(static_cast<double>(m_settings->toneAdjustTreble()) / 100.0);
386 ui->spinBoxAftenSearchSize->setValue(m_settings->aftenExponentSearchSize());
387 ui->spinBoxOpusComplexity->setValue(m_settings->opusComplexity());
389 ui->comboBoxMP3ChannelMode->setCurrentIndex(m_settings->lameChannelMode());
390 ui->comboBoxSamplingRate->setCurrentIndex(m_settings->samplingRate());
391 ui->comboBoxAACProfile->setCurrentIndex(m_settings->aacEncProfile());
392 ui->comboBoxAftenCodingMode->setCurrentIndex(m_settings->aftenAudioCodingMode());
393 ui->comboBoxAftenDRCMode->setCurrentIndex(m_settings->aftenDynamicRangeCompression());
394 ui->comboBoxNormalizationMode->setCurrentIndex(m_settings->normalizationFilterEqualizationMode());
395 //comboBoxOpusOptimize->setCurrentIndex(m_settings->opusOptimizeFor());
396 ui->comboBoxOpusFramesize->setCurrentIndex(m_settings->opusFramesize());
398 SET_CHECKBOX_STATE(ui->checkBoxBitrateManagement, m_settings->bitrateManagementEnabled());
399 SET_CHECKBOX_STATE(ui->checkBoxNeroAAC2PassMode, m_settings->neroAACEnable2Pass());
400 SET_CHECKBOX_STATE(ui->checkBoxAftenFastAllocation, m_settings->aftenFastBitAllocation());
401 SET_CHECKBOX_STATE(ui->checkBoxNormalizationFilter, m_settings->normalizationFilterEnabled());
402 SET_CHECKBOX_STATE(ui->checkBoxAutoDetectInstances, (m_settings->maximumInstances() < 1));
403 SET_CHECKBOX_STATE(ui->checkBoxUseSystemTempFolder, !m_settings->customTempPathEnabled());
404 SET_CHECKBOX_STATE(ui->checkBoxRenameOutput, m_settings->renameOutputFilesEnabled());
405 SET_CHECKBOX_STATE(ui->checkBoxForceStereoDownmix, m_settings->forceStereoDownmix());
406 SET_CHECKBOX_STATE(ui->checkBoxOpusDisableResample, m_settings->opusDisableResample());
407 ui->checkBoxNeroAAC2PassMode->setEnabled(!(m_fhgEncoderAvailable || m_qaacEncoderAvailable));
409 ui->lineEditCustomParamLAME->setText(m_settings->customParametersLAME());
410 ui->lineEditCustomParamOggEnc->setText(m_settings->customParametersOggEnc());
411 ui->lineEditCustomParamNeroAAC->setText(m_settings->customParametersAacEnc());
412 ui->lineEditCustomParamFLAC->setText(m_settings->customParametersFLAC());
413 ui->lineEditCustomParamAften->setText(m_settings->customParametersAften());
414 ui->lineEditCustomParamOpus->setText(m_settings->customParametersOpus());
415 ui->lineEditCustomTempFolder->setText(QDir::toNativeSeparators(m_settings->customTempPath()));
416 ui->lineEditRenamePattern->setText(m_settings->renameOutputFilesPattern());
418 m_evenFilterCustumParamsHelp = new CustomEventFilter();
419 ui->helpCustomParamLAME->installEventFilter(m_evenFilterCustumParamsHelp);
420 ui->helpCustomParamOggEnc->installEventFilter(m_evenFilterCustumParamsHelp);
421 ui->helpCustomParamNeroAAC->installEventFilter(m_evenFilterCustumParamsHelp);
422 ui->helpCustomParamFLAC->installEventFilter(m_evenFilterCustumParamsHelp);
423 ui->helpCustomParamAften->installEventFilter(m_evenFilterCustumParamsHelp);
424 ui->helpCustomParamOpus->installEventFilter(m_evenFilterCustumParamsHelp);
426 m_overwriteButtonGroup = new QButtonGroup(this);
427 m_overwriteButtonGroup->addButton(ui->radioButtonOverwriteModeKeepBoth, SettingsModel::Overwrite_KeepBoth);
428 m_overwriteButtonGroup->addButton(ui->radioButtonOverwriteModeSkipFile, SettingsModel::Overwrite_SkipFile);
429 m_overwriteButtonGroup->addButton(ui->radioButtonOverwriteModeReplaces, SettingsModel::Overwrite_Replaces);
431 ui->radioButtonOverwriteModeKeepBoth->setChecked(m_settings->overwriteMode() == SettingsModel::Overwrite_KeepBoth);
432 ui->radioButtonOverwriteModeSkipFile->setChecked(m_settings->overwriteMode() == SettingsModel::Overwrite_SkipFile);
433 ui->radioButtonOverwriteModeReplaces->setChecked(m_settings->overwriteMode() == SettingsModel::Overwrite_Replaces);
435 connect(ui->sliderLameAlgoQuality, SIGNAL(valueChanged(int)), this, SLOT(updateLameAlgoQuality(int)));
436 connect(ui->checkBoxBitrateManagement, SIGNAL(clicked(bool)), this, SLOT(bitrateManagementEnabledChanged(bool)));
437 connect(ui->spinBoxBitrateManagementMin, SIGNAL(valueChanged(int)), this, SLOT(bitrateManagementMinChanged(int)));
438 connect(ui->spinBoxBitrateManagementMax, SIGNAL(valueChanged(int)), this, SLOT(bitrateManagementMaxChanged(int)));
439 connect(ui->comboBoxMP3ChannelMode, SIGNAL(currentIndexChanged(int)), this, SLOT(channelModeChanged(int)));
440 connect(ui->comboBoxSamplingRate, SIGNAL(currentIndexChanged(int)), this, SLOT(samplingRateChanged(int)));
441 connect(ui->checkBoxNeroAAC2PassMode, SIGNAL(clicked(bool)), this, SLOT(neroAAC2PassChanged(bool)));
442 connect(ui->comboBoxAACProfile, SIGNAL(currentIndexChanged(int)), this, SLOT(neroAACProfileChanged(int)));
443 connect(ui->checkBoxNormalizationFilter, SIGNAL(clicked(bool)), this, SLOT(normalizationEnabledChanged(bool)));
444 connect(ui->comboBoxAftenCodingMode, SIGNAL(currentIndexChanged(int)), this, SLOT(aftenCodingModeChanged(int)));
445 connect(ui->comboBoxAftenDRCMode, SIGNAL(currentIndexChanged(int)), this, SLOT(aftenDRCModeChanged(int)));
446 connect(ui->spinBoxAftenSearchSize, SIGNAL(valueChanged(int)), this, SLOT(aftenSearchSizeChanged(int)));
447 connect(ui->checkBoxAftenFastAllocation, SIGNAL(clicked(bool)), this, SLOT(aftenFastAllocationChanged(bool)));
448 connect(ui->spinBoxNormalizationFilter, SIGNAL(valueChanged(double)), this, SLOT(normalizationMaxVolumeChanged(double)));
449 connect(ui->comboBoxNormalizationMode, SIGNAL(currentIndexChanged(int)), this, SLOT(normalizationModeChanged(int)));
450 connect(ui->spinBoxToneAdjustBass, SIGNAL(valueChanged(double)), this, SLOT(toneAdjustBassChanged(double)));
451 connect(ui->spinBoxToneAdjustTreble, SIGNAL(valueChanged(double)), this, SLOT(toneAdjustTrebleChanged(double)));
452 connect(ui->buttonToneAdjustReset, SIGNAL(clicked()), this, SLOT(toneAdjustTrebleReset()));
453 connect(ui->lineEditCustomParamLAME, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
454 connect(ui->lineEditCustomParamOggEnc, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
455 connect(ui->lineEditCustomParamNeroAAC, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
456 connect(ui->lineEditCustomParamFLAC, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
457 connect(ui->lineEditCustomParamAften, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
458 connect(ui->lineEditCustomParamOpus, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
459 connect(ui->sliderMaxInstances, SIGNAL(valueChanged(int)), this, SLOT(updateMaximumInstances(int)));
460 connect(ui->checkBoxAutoDetectInstances, SIGNAL(clicked(bool)), this, SLOT(autoDetectInstancesChanged(bool)));
461 connect(ui->buttonBrowseCustomTempFolder, SIGNAL(clicked()), this, SLOT(browseCustomTempFolderButtonClicked()));
462 connect(ui->lineEditCustomTempFolder, SIGNAL(textChanged(QString)), this, SLOT(customTempFolderChanged(QString)));
463 connect(ui->checkBoxUseSystemTempFolder, SIGNAL(clicked(bool)), this, SLOT(useCustomTempFolderChanged(bool)));
464 connect(ui->buttonResetAdvancedOptions, SIGNAL(clicked()), this, SLOT(resetAdvancedOptionsButtonClicked()));
465 connect(ui->checkBoxRenameOutput, SIGNAL(clicked(bool)), this, SLOT(renameOutputEnabledChanged(bool)));
466 connect(ui->lineEditRenamePattern, SIGNAL(editingFinished()), this, SLOT(renameOutputPatternChanged()));
467 connect(ui->lineEditRenamePattern, SIGNAL(textChanged(QString)), this, SLOT(renameOutputPatternChanged(QString)));
468 connect(ui->labelShowRenameMacros, SIGNAL(linkActivated(QString)), this, SLOT(showRenameMacros(QString)));
469 connect(ui->checkBoxForceStereoDownmix, SIGNAL(clicked(bool)), this, SLOT(forceStereoDownmixEnabledChanged(bool)));
470 connect(ui->comboBoxOpusFramesize, SIGNAL(currentIndexChanged(int)), this, SLOT(opusSettingsChanged()));
471 connect(ui->spinBoxOpusComplexity, SIGNAL(valueChanged(int)), this, SLOT(opusSettingsChanged()));
472 connect(ui->checkBoxOpusDisableResample, SIGNAL(clicked(bool)), SLOT(opusSettingsChanged()));
473 connect(m_overwriteButtonGroup, SIGNAL(buttonClicked(int)), this, SLOT(overwriteModeChanged(int)));
474 connect(m_evenFilterCustumParamsHelp, SIGNAL(eventOccurred(QWidget*, QEvent*)), this, SLOT(customParamsHelpRequested(QWidget*, QEvent*)));
476 //--------------------------------
477 // Force initial GUI update
478 //--------------------------------
480 updateLameAlgoQuality(ui->sliderLameAlgoQuality->value());
481 updateMaximumInstances(ui->sliderMaxInstances->value());
482 toneAdjustTrebleChanged(ui->spinBoxToneAdjustTreble->value());
483 toneAdjustBassChanged(ui->spinBoxToneAdjustBass->value());
484 customParamsChanged();
486 //--------------------------------
487 // Initialize actions
488 //--------------------------------
490 //Activate file menu actions
491 ui->actionOpenFolder->setData(QVariant::fromValue<bool>(false));
492 ui->actionOpenFolderRecursively->setData(QVariant::fromValue<bool>(true));
493 connect(ui->actionOpenFolder, SIGNAL(triggered()), this, SLOT(openFolderActionActivated()));
494 connect(ui->actionOpenFolderRecursively, SIGNAL(triggered()), this, SLOT(openFolderActionActivated()));
496 //Activate view menu actions
497 m_tabActionGroup = new QActionGroup(this);
498 m_tabActionGroup->addAction(ui->actionSourceFiles);
499 m_tabActionGroup->addAction(ui->actionOutputDirectory);
500 m_tabActionGroup->addAction(ui->actionCompression);
501 m_tabActionGroup->addAction(ui->actionMetaData);
502 m_tabActionGroup->addAction(ui->actionAdvancedOptions);
503 ui->actionSourceFiles->setData(0);
504 ui->actionOutputDirectory->setData(1);
505 ui->actionMetaData->setData(2);
506 ui->actionCompression->setData(3);
507 ui->actionAdvancedOptions->setData(4);
508 ui->actionSourceFiles->setChecked(true);
509 connect(m_tabActionGroup, SIGNAL(triggered(QAction*)), this, SLOT(tabActionActivated(QAction*)));
511 //Activate style menu actions
512 m_styleActionGroup = new QActionGroup(this);
513 m_styleActionGroup->addAction(ui->actionStylePlastique);
514 m_styleActionGroup->addAction(ui->actionStyleCleanlooks);
515 m_styleActionGroup->addAction(ui->actionStyleWindowsVista);
516 m_styleActionGroup->addAction(ui->actionStyleWindowsXP);
517 m_styleActionGroup->addAction(ui->actionStyleWindowsClassic);
518 ui->actionStylePlastique->setData(0);
519 ui->actionStyleCleanlooks->setData(1);
520 ui->actionStyleWindowsVista->setData(2);
521 ui->actionStyleWindowsXP->setData(3);
522 ui->actionStyleWindowsClassic->setData(4);
523 ui->actionStylePlastique->setChecked(true);
524 ui->actionStyleWindowsXP->setEnabled((QSysInfo::windowsVersion() & QSysInfo::WV_NT_based) >= QSysInfo::WV_XP && lamexp_themes_enabled());
525 ui->actionStyleWindowsVista->setEnabled((QSysInfo::windowsVersion() & QSysInfo::WV_NT_based) >= QSysInfo::WV_VISTA && lamexp_themes_enabled());
526 connect(m_styleActionGroup, SIGNAL(triggered(QAction*)), this, SLOT(styleActionActivated(QAction*)));
527 styleActionActivated(NULL);
529 //Populate the language menu
530 m_languageActionGroup = new QActionGroup(this);
531 QStringList translations = lamexp_query_translations();
532 while(!translations.isEmpty())
534 QString langId = translations.takeFirst();
535 QAction *currentLanguage = new QAction(this);
536 currentLanguage->setData(langId);
537 currentLanguage->setText(lamexp_translation_name(langId));
538 currentLanguage->setIcon(QIcon(QString(":/flags/%1.png").arg(langId)));
539 currentLanguage->setCheckable(true);
540 currentLanguage->setChecked(false);
541 m_languageActionGroup->addAction(currentLanguage);
542 ui->menuLanguage->insertAction(ui->actionLoadTranslationFromFile, currentLanguage);
544 ui->menuLanguage->insertSeparator(ui->actionLoadTranslationFromFile);
545 connect(ui->actionLoadTranslationFromFile, SIGNAL(triggered(bool)), this, SLOT(languageFromFileActionActivated(bool)));
546 connect(m_languageActionGroup, SIGNAL(triggered(QAction*)), this, SLOT(languageActionActivated(QAction*)));
547 ui->actionLoadTranslationFromFile->setChecked(false);
549 //Activate tools menu actions
550 ui->actionDisableUpdateReminder->setChecked(!m_settings->autoUpdateEnabled());
551 ui->actionDisableSounds->setChecked(!m_settings->soundsEnabled());
552 ui->actionDisableNeroAacNotifications->setChecked(!m_settings->neroAacNotificationsEnabled());
553 ui->actionDisableSlowStartupNotifications->setChecked(!m_settings->antivirNotificationsEnabled());
554 ui->actionDisableShellIntegration->setChecked(!m_settings->shellIntegrationEnabled());
555 ui->actionDisableShellIntegration->setDisabled(lamexp_portable_mode() && ui->actionDisableShellIntegration->isChecked());
556 ui->actionCheckForBetaUpdates->setChecked(m_settings->autoUpdateCheckBeta() || lamexp_version_demo());
557 ui->actionCheckForBetaUpdates->setEnabled(!lamexp_version_demo());
558 ui->actionHibernateComputer->setChecked(m_settings->hibernateComputer());
559 ui->actionHibernateComputer->setEnabled(lamexp_is_hibernation_supported());
560 connect(ui->actionDisableUpdateReminder, SIGNAL(triggered(bool)), this, SLOT(disableUpdateReminderActionTriggered(bool)));
561 connect(ui->actionDisableSounds, SIGNAL(triggered(bool)), this, SLOT(disableSoundsActionTriggered(bool)));
562 connect(ui->actionDisableNeroAacNotifications, SIGNAL(triggered(bool)), this, SLOT(disableNeroAacNotificationsActionTriggered(bool)));
563 connect(ui->actionDisableSlowStartupNotifications, SIGNAL(triggered(bool)), this, SLOT(disableSlowStartupNotificationsActionTriggered(bool)));
564 connect(ui->actionDisableShellIntegration, SIGNAL(triggered(bool)), this, SLOT(disableShellIntegrationActionTriggered(bool)));
565 connect(ui->actionShowDropBoxWidget, SIGNAL(triggered(bool)), this, SLOT(showDropBoxWidgetActionTriggered(bool)));
566 connect(ui->actionHibernateComputer, SIGNAL(triggered(bool)), this, SLOT(hibernateComputerActionTriggered(bool)));
567 connect(ui->actionCheckForBetaUpdates, SIGNAL(triggered(bool)), this, SLOT(checkForBetaUpdatesActionTriggered(bool)));
568 connect(ui->actionImportCueSheet, SIGNAL(triggered(bool)), this, SLOT(importCueSheetActionTriggered(bool)));
570 //Activate help menu actions
571 ui->actionVisitHomepage->setData(QString::fromLatin1(lamexp_website_url()));
572 ui->actionVisitSupport->setData(QString::fromLatin1(lamexp_support_url()));
573 ui->actionVisitMuldersSite->setData(QString::fromLatin1(lamexp_mulders_url()));
574 ui->actionDocumentFAQ->setData(QString("%1/FAQ.html").arg(QApplication::applicationDirPath()));
575 ui->actionDocumentChangelog->setData(QString("%1/Changelog.html").arg(QApplication::applicationDirPath()));
576 ui->actionDocumentTranslate->setData(QString("%1/Translate.html").arg(QApplication::applicationDirPath()));
577 connect(ui->actionCheckUpdates, SIGNAL(triggered()), this, SLOT(checkUpdatesActionActivated()));
578 connect(ui->actionVisitHomepage, SIGNAL(triggered()), this, SLOT(visitHomepageActionActivated()));
579 connect(ui->actionVisitMuldersSite, SIGNAL(triggered()), this, SLOT(visitHomepageActionActivated()));
580 connect(ui->actionVisitSupport, SIGNAL(triggered()), this, SLOT(visitHomepageActionActivated()));
581 connect(ui->actionDocumentFAQ, SIGNAL(triggered()), this, SLOT(documentActionActivated()));
582 connect(ui->actionDocumentChangelog, SIGNAL(triggered()), this, SLOT(documentActionActivated()));
583 connect(ui->actionDocumentTranslate, SIGNAL(triggered()), this, SLOT(documentActionActivated()));
585 //--------------------------------
586 // Prepare to show window
587 //--------------------------------
589 //Center window in screen
590 QRect desktopRect = QApplication::desktop()->screenGeometry();
591 QRect thisRect = this->geometry();
592 move((desktopRect.width() - thisRect.width()) / 2, (desktopRect.height() - thisRect.height()) / 2);
593 setMinimumSize(thisRect.width(), thisRect.height());
596 m_banner = new WorkingBanner(this);
598 //Create DropBox widget
599 m_dropBox = new DropBox(this, m_fileListModel, m_settings);
600 connect(m_fileListModel, SIGNAL(modelReset()), m_dropBox, SLOT(modelChanged()));
601 connect(m_fileListModel, SIGNAL(rowsInserted(QModelIndex,int,int)), m_dropBox, SLOT(modelChanged()));
602 connect(m_fileListModel, SIGNAL(rowsRemoved(QModelIndex,int,int)), m_dropBox, SLOT(modelChanged()));
603 connect(m_fileListModel, SIGNAL(rowAppended()), m_dropBox, SLOT(modelChanged()));
605 //Create message handler thread
606 m_messageHandler = new MessageHandlerThread();
607 m_delayedFileList = new QStringList();
608 m_delayedFileTimer = new QTimer();
609 m_delayedFileTimer->setSingleShot(true);
610 m_delayedFileTimer->setInterval(5000);
611 connect(m_messageHandler, SIGNAL(otherInstanceDetected()), this, SLOT(notifyOtherInstance()), Qt::QueuedConnection);
612 connect(m_messageHandler, SIGNAL(fileReceived(QString)), this, SLOT(addFileDelayed(QString)), Qt::QueuedConnection);
613 connect(m_messageHandler, SIGNAL(folderReceived(QString, bool)), this, SLOT(addFolderDelayed(QString, bool)), Qt::QueuedConnection);
614 connect(m_messageHandler, SIGNAL(killSignalReceived()), this, SLOT(close()), Qt::QueuedConnection);
615 connect(m_delayedFileTimer, SIGNAL(timeout()), this, SLOT(handleDelayedFiles()));
616 m_messageHandler->start();
619 initializeTranslation();
621 //Re-translate (make sure we translate once)
622 QEvent languageChangeEvent(QEvent::LanguageChange);
623 changeEvent(&languageChangeEvent);
626 this->setAcceptDrops(true);
629 ////////////////////////////////////////////////////////////
631 ////////////////////////////////////////////////////////////
633 MainWindow::~MainWindow(void)
635 //Stop message handler thread
636 if(m_messageHandler && m_messageHandler->isRunning())
638 m_messageHandler->stop();
639 if(!m_messageHandler->wait(2500))
641 m_messageHandler->terminate();
642 m_messageHandler->wait();
647 SET_MODEL(ui->sourceFileView, NULL);
648 SET_MODEL(ui->outputFolderView, NULL);
649 SET_MODEL(ui->metaDataView, NULL);
652 LAMEXP_DELETE(m_tabActionGroup);
653 LAMEXP_DELETE(m_styleActionGroup);
654 LAMEXP_DELETE(m_languageActionGroup);
655 LAMEXP_DELETE(m_banner);
656 LAMEXP_DELETE(m_fileSystemModel);
657 LAMEXP_DELETE(m_messageHandler);
658 LAMEXP_DELETE(m_delayedFileList);
659 LAMEXP_DELETE(m_delayedFileTimer);
660 LAMEXP_DELETE(m_metaInfoModel);
661 LAMEXP_DELETE(m_encoderButtonGroup);
662 LAMEXP_DELETE(m_modeButtonGroup);
663 LAMEXP_DELETE(m_overwriteButtonGroup);
664 LAMEXP_DELETE(m_sourceFilesContextMenu);
665 LAMEXP_DELETE(m_outputFolderFavoritesMenu);
666 LAMEXP_DELETE(m_outputFolderContextMenu);
667 LAMEXP_DELETE(m_dropBox);
668 LAMEXP_DELETE(m_evenFilterCustumParamsHelp);
669 LAMEXP_DELETE(m_evenFilterOutputFolderMouse);
670 LAMEXP_DELETE(m_evenFilterOutputFolderView);
671 LAMEXP_DELETE(m_evenFilterCompressionTab);
673 //Un-initialize the dialog
677 ////////////////////////////////////////////////////////////
679 ////////////////////////////////////////////////////////////
682 * Add file to source list
684 void MainWindow::addFiles(const QStringList &files)
691 ui->tabWidget->setCurrentIndex(0);
693 FileAnalyzer *analyzer = new FileAnalyzer(files);
694 connect(analyzer, SIGNAL(fileSelected(QString)), m_banner, SLOT(setText(QString)), Qt::QueuedConnection);
695 connect(analyzer, SIGNAL(progressValChanged(unsigned int)), m_banner, SLOT(setProgressVal(unsigned int)), Qt::QueuedConnection);
696 connect(analyzer, SIGNAL(progressMaxChanged(unsigned int)), m_banner, SLOT(setProgressMax(unsigned int)), Qt::QueuedConnection);
697 connect(analyzer, SIGNAL(fileAnalyzed(AudioFileModel)), m_fileListModel, SLOT(addFile(AudioFileModel)), Qt::QueuedConnection);
698 connect(m_banner, SIGNAL(userAbort()), analyzer, SLOT(abortProcess()), Qt::DirectConnection);
702 m_fileListModel->setBlockUpdates(true);
703 QTime startTime = QTime::currentTime();
704 m_banner->show(tr("Adding file(s), please wait..."), analyzer);
708 /* ignore any exceptions that may occur */
711 m_fileListModel->setBlockUpdates(false);
712 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
713 ui->sourceFileView->update();
714 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
715 ui->sourceFileView->scrollToBottom();
716 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
718 if(analyzer->filesDenied())
720 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."))));
722 if(analyzer->filesDummyCDDA())
724 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>"))));
726 if(analyzer->filesCueSheet())
728 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."))));
730 if(analyzer->filesRejected())
732 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."))));
735 LAMEXP_DELETE(analyzer);
740 * Add folder to source list
742 void MainWindow::addFolder(const QString &path, bool recursive, bool delayed)
744 QFileInfoList folderInfoList;
745 folderInfoList << QFileInfo(path);
746 QStringList fileList;
748 m_banner->show(tr("Scanning folder(s) for files, please wait..."));
750 QApplication::processEvents();
751 GetAsyncKeyState(VK_ESCAPE);
753 while(!folderInfoList.isEmpty())
755 if(GetAsyncKeyState(VK_ESCAPE) & 0x0001)
757 MessageBeep(MB_ICONERROR);
758 qWarning("Operation cancelled by user!");
763 QDir currentDir(folderInfoList.takeFirst().canonicalFilePath());
764 QFileInfoList fileInfoList = currentDir.entryInfoList(QDir::Files | QDir::NoSymLinks);
766 while(!fileInfoList.isEmpty())
768 fileList << fileInfoList.takeFirst().canonicalFilePath();
771 QApplication::processEvents();
775 folderInfoList.append(currentDir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks));
776 QApplication::processEvents();
781 QApplication::processEvents();
783 if(!fileList.isEmpty())
787 addFilesDelayed(fileList);
799 bool MainWindow::checkForUpdates(void)
801 bool bReadyToInstall = false;
803 UpdateDialog *updateDialog = new UpdateDialog(m_settings, this);
804 updateDialog->exec();
806 if(updateDialog->getSuccess())
808 m_settings->autoUpdateLastCheck(QDate::currentDate().toString(Qt::ISODate));
809 bReadyToInstall = updateDialog->updateReadyToInstall();
812 LAMEXP_DELETE(updateDialog);
813 return bReadyToInstall;
817 * Refresh list of favorites
819 void MainWindow::refreshFavorites(void)
821 QList<QAction*> folderList = m_outputFolderFavoritesMenu->actions();
822 QStringList favorites = m_settings->favoriteOutputFolders().split("|", QString::SkipEmptyParts);
823 while(favorites.count() > 6) favorites.removeFirst();
825 while(!folderList.isEmpty())
827 QAction *currentItem = folderList.takeFirst();
828 if(currentItem->isSeparator()) break;
829 m_outputFolderFavoritesMenu->removeAction(currentItem);
830 LAMEXP_DELETE(currentItem);
833 QAction *lastItem = m_outputFolderFavoritesMenu->actions().first();
835 while(!favorites.isEmpty())
837 QString path = favorites.takeLast();
838 if(QDir(path).exists())
840 QAction *action = new QAction(QIcon(":/icons/folder_go.png"), QDir::toNativeSeparators(path), this);
841 action->setData(path);
842 m_outputFolderFavoritesMenu->insertAction(lastItem, action);
843 connect(action, SIGNAL(triggered(bool)), this, SLOT(gotoFavoriteFolder()));
850 * Initilaize translation
852 void MainWindow::initializeTranslation(void)
854 bool translationLoaded = false;
856 //Try to load "external" translation file
857 if(!m_settings->currentLanguageFile().isEmpty())
859 const QString qmFilePath = QFileInfo(m_settings->currentLanguageFile()).canonicalFilePath();
860 if((!qmFilePath.isEmpty()) && QFileInfo(qmFilePath).exists() && QFileInfo(qmFilePath).isFile() && (QFileInfo(qmFilePath).suffix().compare("qm", Qt::CaseInsensitive) == 0))
862 if(lamexp_install_translator_from_file(qmFilePath))
864 QList<QAction*> actions = m_languageActionGroup->actions();
865 while(!actions.isEmpty()) actions.takeFirst()->setChecked(false);
866 ui->actionLoadTranslationFromFile->setChecked(true);
867 translationLoaded = true;
872 //Try to load "built-in" translation file
873 if(!translationLoaded)
875 QList<QAction*> languageActions = m_languageActionGroup->actions();
876 while(!languageActions.isEmpty())
878 QAction *currentLanguage = languageActions.takeFirst();
879 if(currentLanguage->data().toString().compare(m_settings->currentLanguage(), Qt::CaseInsensitive) == 0)
881 currentLanguage->setChecked(true);
882 languageActionActivated(currentLanguage);
883 translationLoaded = true;
888 //Fallback to default translation
889 if(!translationLoaded)
891 QList<QAction*> languageActions = m_languageActionGroup->actions();
892 while(!languageActions.isEmpty())
894 QAction *currentLanguage = languageActions.takeFirst();
895 if(currentLanguage->data().toString().compare(LAMEXP_DEFAULT_LANGID, Qt::CaseInsensitive) == 0)
897 currentLanguage->setChecked(true);
898 languageActionActivated(currentLanguage);
899 translationLoaded = true;
904 //Make sure we loaded some translation
905 if(!translationLoaded)
907 qFatal("Failed to load any translation, this is NOT supposed to happen!");
911 ////////////////////////////////////////////////////////////
913 ////////////////////////////////////////////////////////////
916 * Window is about to be shown
918 void MainWindow::showEvent(QShowEvent *event)
921 m_dropNoteLabel->setGeometry(0, 0, ui->sourceFileView->width(), ui->sourceFileView->height());
922 sourceModelChanged();
924 if(!event->spontaneous())
926 ui->tabWidget->setCurrentIndex(0);
931 m_firstTimeShown = false;
932 QTimer::singleShot(0, this, SLOT(windowShown()));
936 if(m_settings->dropBoxWidgetEnabled())
938 m_dropBox->setVisible(true);
944 * Re-translate the UI
946 void MainWindow::changeEvent(QEvent *e)
948 if(e->type() == QEvent::LanguageChange)
950 int comboBoxIndex[8];
952 //Backup combobox indices, as retranslateUi() resets
953 comboBoxIndex[0] = ui->comboBoxMP3ChannelMode->currentIndex();
954 comboBoxIndex[1] = ui->comboBoxSamplingRate->currentIndex();
955 comboBoxIndex[2] = ui->comboBoxAACProfile->currentIndex();
956 comboBoxIndex[3] = ui->comboBoxAftenCodingMode->currentIndex();
957 comboBoxIndex[4] = ui->comboBoxAftenDRCMode->currentIndex();
958 comboBoxIndex[5] = ui->comboBoxNormalizationMode->currentIndex();
959 comboBoxIndex[6] = 0; //comboBoxOpusOptimize->currentIndex();
960 comboBoxIndex[7] = ui->comboBoxOpusFramesize->currentIndex();
962 //Re-translate from UIC
963 ui->retranslateUi(this);
965 //Restore combobox indices
966 ui->comboBoxMP3ChannelMode->setCurrentIndex(comboBoxIndex[0]);
967 ui->comboBoxSamplingRate->setCurrentIndex(comboBoxIndex[1]);
968 ui->comboBoxAACProfile->setCurrentIndex(comboBoxIndex[2]);
969 ui->comboBoxAftenCodingMode->setCurrentIndex(comboBoxIndex[3]);
970 ui->comboBoxAftenDRCMode->setCurrentIndex(comboBoxIndex[4]);
971 ui->comboBoxNormalizationMode->setCurrentIndex(comboBoxIndex[5]);
972 //comboBoxOpusOptimize->setCurrentIndex(comboBoxIndex[6]);
973 ui->comboBoxOpusFramesize->setCurrentIndex(comboBoxIndex[7]);
975 //Update the window title
978 setWindowTitle(QString("%1 [!!! DEBUG BUILD !!!]").arg(windowTitle()));
980 else if(lamexp_version_demo())
982 setWindowTitle(QString("%1 [%2]").arg(windowTitle(), tr("DEMO VERSION")));
985 //Manually re-translate widgets that UIC doesn't handle
986 m_dropNoteLabel->setText(QString("» %1 «").arg(tr("You can drop in audio files here!")));
987 m_outputFolderNoteBox->setText(tr("Initializing directory outline, please be patient..."));
988 m_showDetailsContextAction->setText(tr("Show Details"));
989 m_previewContextAction->setText(tr("Open File in External Application"));
990 m_findFileContextAction->setText(tr("Browse File Location"));
991 m_showFolderContextAction->setText(tr("Browse Selected Folder"));
992 m_refreshFolderContextAction->setText(tr("Refresh Directory Outline"));
993 m_goUpFolderContextAction->setText(tr("Go To Parent Directory"));
994 m_addFavoriteFolderAction->setText(tr("Bookmark Current Output Folder"));
995 m_exportCsvContextAction->setText(tr("Export Meta Tags to CSV File"));
996 m_importCsvContextAction->setText(tr("Import Meta Tags from CSV File"));
999 m_metaInfoModel->clearData();
1000 m_metaInfoModel->setData(m_metaInfoModel->index(4, 1), m_settings->metaInfoPosition());
1001 updateEncoder(m_settings->compressionEncoder());
1002 updateLameAlgoQuality(ui->sliderLameAlgoQuality->value());
1003 updateMaximumInstances(ui->sliderMaxInstances->value());
1004 renameOutputPatternChanged(ui->lineEditRenamePattern->text(), true);
1006 //Re-install shell integration
1007 if(m_settings->shellIntegrationEnabled())
1009 ShellIntegration::install();
1012 //Translate system menu
1013 if(HMENU hMenu = ::GetSystemMenu(winId(), FALSE))
1015 ModifyMenu(hMenu, IDM_ABOUTBOX, MF_STRING | MF_BYCOMMAND, IDM_ABOUTBOX, QWCHAR(ui->buttonAbout->text()));
1018 //Force resize, if needed
1019 tabPageChanged(ui->tabWidget->currentIndex());
1024 * File dragged over window
1026 void MainWindow::dragEnterEvent(QDragEnterEvent *event)
1028 QStringList formats = event->mimeData()->formats();
1030 if(formats.contains("application/x-qt-windows-mime;value=\"FileNameW\"", Qt::CaseInsensitive) && formats.contains("text/uri-list", Qt::CaseInsensitive))
1032 event->acceptProposedAction();
1037 * File dropped onto window
1039 void MainWindow::dropEvent(QDropEvent *event)
1043 QStringList droppedFiles;
1044 QList<QUrl> urls = event->mimeData()->urls();
1046 while(!urls.isEmpty())
1048 QUrl currentUrl = urls.takeFirst();
1049 QFileInfo file(currentUrl.toLocalFile());
1056 qDebug("Dropped File: %s", file.canonicalFilePath().toUtf8().constData());
1057 droppedFiles << file.canonicalFilePath();
1062 qDebug("Dropped Folder: %s", file.canonicalFilePath().toUtf8().constData());
1063 QList<QFileInfo> list = QDir(file.canonicalFilePath()).entryInfoList(QDir::Files | QDir::NoSymLinks);
1064 if(list.count() > 0)
1066 for(int j = 0; j < list.count(); j++)
1068 droppedFiles << list.at(j).canonicalFilePath();
1073 list = QDir(file.canonicalFilePath()).entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks);
1074 for(int j = 0; j < list.count(); j++)
1076 qDebug("Descending to Folder: %s", list.at(j).canonicalFilePath().toUtf8().constData());
1077 urls.prepend(QUrl::fromLocalFile(list.at(j).canonicalFilePath()));
1083 if(!droppedFiles.isEmpty())
1085 addFilesDelayed(droppedFiles, true);
1090 * Window tries to close
1092 void MainWindow::closeEvent(QCloseEvent *event)
1094 if(m_banner->isVisible() || m_delayedFileTimer->isActive())
1096 MessageBeep(MB_ICONEXCLAMATION);
1107 * Window was resized
1109 void MainWindow::resizeEvent(QResizeEvent *event)
1111 if(event) QMainWindow::resizeEvent(event);
1112 m_dropNoteLabel->setGeometry(0, 0, ui->sourceFileView->width(), ui->sourceFileView->height());
1114 if(QWidget *port = ui->outputFolderView->viewport())
1116 m_outputFolderNoteBox->setGeometry(16, (port->height() - 64) / 2, port->width() - 32, 64);
1121 * Key press event filter
1123 void MainWindow::keyPressEvent(QKeyEvent *e)
1125 if(e->key() == Qt::Key_Delete)
1127 if(ui->sourceFileView->isVisible())
1129 QTimer::singleShot(0, this, SLOT(removeFileButtonClicked()));
1134 if(e->modifiers().testFlag(Qt::ControlModifier) && (e->key() == Qt::Key_F5))
1136 initializeTranslation();
1137 MessageBeep(MB_ICONINFORMATION);
1141 if(e->key() == Qt::Key_F5)
1143 if(ui->outputFolderView->isVisible())
1145 QTimer::singleShot(0, this, SLOT(refreshFolderContextActionTriggered()));
1150 QMainWindow::keyPressEvent(e);
1156 bool MainWindow::eventFilter(QObject *obj, QEvent *event)
1158 if(obj == m_fileSystemModel)
1160 if(QApplication::overrideCursor() == NULL)
1162 QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
1163 QTimer::singleShot(250, this, SLOT(restoreCursor()));
1167 return QMainWindow::eventFilter(obj, event);
1170 bool MainWindow::event(QEvent *e)
1174 case lamexp_event_queryendsession:
1175 qWarning("System is shutting down, main window prepares to close...");
1176 if(m_banner->isVisible()) m_banner->close();
1177 if(m_delayedFileTimer->isActive()) m_delayedFileTimer->stop();
1179 case lamexp_event_endsession:
1180 qWarning("System is shutting down, main window will close now...");
1185 QApplication::processEvents(QEventLoop::WaitForMoreEvents & QEventLoop::ExcludeUserInputEvents);
1188 m_fileListModel->clearFiles();
1190 case QEvent::MouseButtonPress:
1191 if(ui->outputFolderEdit->isVisible())
1193 QTimer::singleShot(0, this, SLOT(outputFolderEditFinished()));
1196 return QMainWindow::event(e);
1200 bool MainWindow::winEvent(MSG *message, long *result)
1202 if((message->message == WM_SYSCOMMAND) && ((message->wParam & 0xFFF0) == IDM_ABOUTBOX))
1204 QTimer::singleShot(0, ui->buttonAbout, SLOT(click()));
1208 return WinSevenTaskbar::handleWinEvent(message, result);
1211 ////////////////////////////////////////////////////////////
1213 ////////////////////////////////////////////////////////////
1215 // =========================================================
1216 // Show window slots
1217 // =========================================================
1222 void MainWindow::windowShown(void)
1224 const QStringList &arguments = lamexp_arguments(); //QApplication::arguments();
1227 bool firstRun = false;
1228 for(int i = 0; i < arguments.count(); i++)
1230 /*QMessageBox::information(this, QString::number(i), arguments[i]);*/
1231 if(!arguments[i].compare("--first-run", Qt::CaseInsensitive)) firstRun = true;
1235 if((m_settings->licenseAccepted() <= 0) || firstRun)
1237 int iAccepted = m_settings->licenseAccepted();
1239 if((iAccepted == 0) || firstRun)
1241 AboutDialog *about = new AboutDialog(m_settings, this, true);
1242 iAccepted = about->exec();
1243 if(iAccepted <= 0) iAccepted = -2;
1244 LAMEXP_DELETE(about);
1249 m_settings->licenseAccepted(++iAccepted);
1250 m_settings->syncNow();
1251 QApplication::processEvents();
1252 PlaySound(MAKEINTRESOURCE(IDR_WAVE_WHAMMY), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
1253 QMessageBox::critical(this, tr("License Declined"), tr("You have declined the license. Consequently the application will exit now!"), tr("Goodbye!"));
1254 QFileInfo uninstallerInfo = QFileInfo(QString("%1/Uninstall.exe").arg(QApplication::applicationDirPath()));
1255 if(uninstallerInfo.exists())
1257 QString uninstallerDir = uninstallerInfo.canonicalPath();
1258 QString uninstallerPath = uninstallerInfo.canonicalFilePath();
1259 for(int i = 0; i < 3; i++)
1261 HINSTANCE res = ShellExecuteW(reinterpret_cast<HWND>(this->winId()), L"open", QWCHAR(QDir::toNativeSeparators(uninstallerPath)), L"/Force", QWCHAR(QDir::toNativeSeparators(uninstallerDir)), SW_SHOWNORMAL);
1262 if(reinterpret_cast<int>(res) > 32) break;
1265 QApplication::quit();
1269 PlaySound(MAKEINTRESOURCE(IDR_WAVE_WOOHOO), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
1270 m_settings->licenseAccepted(1);
1271 m_settings->syncNow();
1272 if(lamexp_version_demo()) showAnnounceBox();
1275 //Check for expiration
1276 if(lamexp_version_demo())
1278 if(lamexp_current_date_safe() >= lamexp_version_expires())
1280 qWarning("Binary has expired !!!");
1281 PlaySound(MAKEINTRESOURCE(IDR_WAVE_WHAMMY), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
1282 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)
1286 QApplication::quit();
1291 //Slow startup indicator
1292 if(m_settings->slowStartup() && m_settings->antivirNotificationsEnabled())
1295 message += NOBR(tr("It seems that a bogus anti-virus software is slowing down the startup of LameXP.")).append("<br>");
1296 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>");
1297 if(QMessageBox::warning(this, tr("Slow Startup"), message, tr("Discard"), tr("Don't Show Again")) == 1)
1299 m_settings->antivirNotificationsEnabled(false);
1300 ui->actionDisableSlowStartupNotifications->setChecked(!m_settings->antivirNotificationsEnabled());
1305 if(lamexp_current_date_safe() >= lamexp_version_date().addYears(1))
1307 qWarning("Binary is more than a year old, time to update!");
1308 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"));
1312 if(checkForUpdates())
1314 QApplication::quit();
1319 QApplication::quit();
1322 QEventLoop loop; QTimer::singleShot(7000, &loop, SLOT(quit()));
1323 PlaySound(MAKEINTRESOURCE(IDR_WAVE_WAITING), GetModuleHandle(NULL), SND_RESOURCE | SND_ASYNC);
1324 m_banner->show(tr("Skipping update check this time, please be patient..."), &loop);
1328 else if(m_settings->autoUpdateEnabled())
1330 QDate lastUpdateCheck = QDate::fromString(m_settings->autoUpdateLastCheck(), Qt::ISODate);
1331 if(!firstRun && (!lastUpdateCheck.isValid() || lamexp_current_date_safe() >= lastUpdateCheck.addDays(14)))
1333 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)
1335 if(checkForUpdates())
1337 QApplication::quit();
1344 //Check for AAC support
1345 if(m_neroEncoderAvailable)
1347 if(m_settings->neroAacNotificationsEnabled())
1349 if(lamexp_tool_version("neroAacEnc.exe") < lamexp_toolver_neroaac())
1351 QString messageText;
1352 messageText += NOBR(tr("LameXP detected that your version of the Nero AAC encoder is outdated!")).append("<br>");
1353 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>");
1354 messageText += NOBR(tr("You can download the latest version of the Nero AAC encoder from the Nero website at:")).append("<br>");
1355 messageText += "<nobr><tt>" + LINK(AboutDialog::neroAacUrl) + "</tt></nobr><br><br>";
1356 messageText += NOBR(tr("(Hint: Please ignore the name of the downloaded ZIP file and check the included 'changelog.txt' instead!)")).append("<br>");
1357 QMessageBox::information(this, tr("AAC Encoder Outdated"), messageText);
1363 if(m_settings->neroAacNotificationsEnabled() && (!(m_fhgEncoderAvailable || m_qaacEncoderAvailable)))
1365 QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
1366 if(appPath.isEmpty()) appPath = QCoreApplication::applicationDirPath();
1367 QString messageText;
1368 messageText += NOBR(tr("The Nero AAC encoder could not be found. AAC encoding support will be disabled.")).append("<br>");
1369 messageText += NOBR(tr("Please put 'neroAacEnc.exe', 'neroAacDec.exe' and 'neroAacTag.exe' into the LameXP directory!")).append("<br><br>");
1370 messageText += NOBR(tr("Your LameXP directory is located here:")).append("<br>");
1371 messageText += QString("<nobr><tt>%1</tt></nobr><br><br>").arg(FSLINK(QDir::toNativeSeparators(appPath)));
1372 messageText += NOBR(tr("You can download the Nero AAC encoder for free from the official Nero website at:")).append("<br>");
1373 messageText += "<nobr><tt>" + LINK(AboutDialog::neroAacUrl) + "</tt></nobr><br>";
1374 if(QMessageBox::information(this, tr("AAC Support Disabled"), messageText, tr("Discard"), tr("Don't Show Again")) == 1)
1376 m_settings->neroAacNotificationsEnabled(false);
1377 ui->actionDisableNeroAacNotifications->setChecked(!m_settings->neroAacNotificationsEnabled());
1382 //Add files from the command-line
1383 for(int i = 0; i < arguments.count() - 1; i++)
1385 QStringList addedFiles;
1386 if(!arguments[i].compare("--add", Qt::CaseInsensitive))
1388 QFileInfo currentFile(arguments[++i].trimmed());
1389 qDebug("Adding file from CLI: %s", currentFile.absoluteFilePath().toUtf8().constData());
1390 addedFiles.append(currentFile.absoluteFilePath());
1392 if(!addedFiles.isEmpty())
1394 addFilesDelayed(addedFiles);
1398 //Add folders from the command-line
1399 for(int i = 0; i < arguments.count() - 1; i++)
1401 if(!arguments[i].compare("--add-folder", Qt::CaseInsensitive))
1403 QFileInfo currentFile(arguments[++i].trimmed());
1404 qDebug("Adding folder from CLI: %s", currentFile.absoluteFilePath().toUtf8().constData());
1405 addFolder(currentFile.absoluteFilePath(), false, true);
1407 if(!arguments[i].compare("--add-recursive", Qt::CaseInsensitive))
1409 QFileInfo currentFile(arguments[++i].trimmed());
1410 qDebug("Adding folder recursively from CLI: %s", currentFile.absoluteFilePath().toUtf8().constData());
1411 addFolder(currentFile.absoluteFilePath(), true, true);
1415 //Enable shell integration
1416 if(m_settings->shellIntegrationEnabled())
1418 ShellIntegration::install();
1421 //Make DropBox visible
1422 if(m_settings->dropBoxWidgetEnabled())
1424 m_dropBox->setVisible(true);
1431 void MainWindow::showAnnounceBox(void)
1433 const unsigned int timeout = 8U;
1435 const QString announceText = QString("%1<br><br>%2<br><nobr><tt>%3</tt></nobr><br>").arg
1437 NOBR("We are still looking for LameXP translators!"),
1438 NOBR("If you are willing to translate LameXP to your language or to complete an existing translation, please refer to:"),
1439 LINK("http://lamexp.sourceforge.net/doc/Translate.html")
1442 QMessageBox *announceBox = new QMessageBox(QMessageBox::Warning, "We want you!", announceText, QMessageBox::NoButton, this);
1443 announceBox->setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
1444 announceBox->setIconPixmap(QIcon(":/images/Announcement.png").pixmap(64,79));
1446 QTimer *timers[timeout+1];
1447 QPushButton *buttons[timeout+1];
1449 for(unsigned int i = 0; i <= timeout; i++)
1451 QString text = (i > 0) ? QString("%1 (%2)").arg(tr("Discard"), QString::number(i)) : tr("Discard");
1452 buttons[i] = announceBox->addButton(text, (i > 0) ? QMessageBox::NoRole : QMessageBox::AcceptRole);
1455 for(unsigned int i = 0; i <= timeout; i++)
1457 buttons[i]->setEnabled(i == 0);
1458 buttons[i]->setVisible(i == timeout);
1461 for(unsigned int i = 0; i < timeout; i++)
1463 timers[i] = new QTimer(this);
1464 timers[i]->setSingleShot(true);
1465 timers[i]->setInterval(1000);
1466 connect(timers[i], SIGNAL(timeout()), buttons[i+1], SLOT(hide()));
1467 connect(timers[i], SIGNAL(timeout()), buttons[i], SLOT(show()));
1470 connect(timers[i], SIGNAL(timeout()), timers[i-1], SLOT(start()));
1474 timers[timeout-1]->start();
1475 announceBox->exec();
1477 for(unsigned int i = 0; i < timeout; i++)
1480 LAMEXP_DELETE(timers[i]);
1483 LAMEXP_DELETE(announceBox);
1486 // =========================================================
1487 // Main button solots
1488 // =========================================================
1493 void MainWindow::encodeButtonClicked(void)
1495 static const unsigned __int64 oneGigabyte = 1073741824ui64;
1496 static const unsigned __int64 minimumFreeDiskspaceMultiplier = 2ui64;
1497 static const char *writeTestBuffer = "LAMEXP_WRITE_TEST";
1501 if(m_fileListModel->rowCount() < 1)
1503 QMessageBox::warning(this, tr("LameXP"), NOBR(tr("You must add at least one file to the list before proceeding!")));
1504 ui->tabWidget->setCurrentIndex(0);
1508 QString tempFolder = m_settings->customTempPathEnabled() ? m_settings->customTempPath() : lamexp_temp_folder2();
1509 if(!QFileInfo(tempFolder).exists() || !QFileInfo(tempFolder).isDir())
1511 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)
1513 SET_CHECKBOX_STATE(ui->checkBoxUseSystemTempFolder, m_settings->customTempPathEnabledDefault());
1519 unsigned __int64 currentFreeDiskspace = lamexp_free_diskspace(tempFolder, &ok);
1521 if(ok && (currentFreeDiskspace < (oneGigabyte * minimumFreeDiskspaceMultiplier)))
1523 QStringList tempFolderParts = tempFolder.split("/", QString::SkipEmptyParts, Qt::CaseInsensitive);
1524 tempFolderParts.takeLast();
1525 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_WHAMMY), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
1526 QString lowDiskspaceMsg = QString("%1<br>%2<br><br>%3<br>%4<br>").arg
1528 NOBR(tr("There are less than %1 GB of free diskspace available on your system's TEMP folder.").arg(QString::number(minimumFreeDiskspaceMultiplier))),
1529 NOBR(tr("It is highly recommend to free up more diskspace before proceeding with the encode!")),
1530 NOBR(tr("Your TEMP folder is located at:")),
1531 QString("<nobr><tt>%1</tt></nobr>").arg(FSLINK(tempFolderParts.join("\\")))
1533 switch(QMessageBox::warning(this, tr("Low Diskspace Warning"), lowDiskspaceMsg, tr("Abort Encoding Process"), tr("Clean Disk Now"), tr("Ignore")))
1536 QProcess::startDetached(QString("%1/cleanmgr.exe").arg(lamexp_known_folder(lamexp_folder_systemfolder)), QStringList() << "/D" << tempFolderParts.first());
1541 QMessageBox::warning(this, tr("Low Diskspace"), NOBR(tr("You are proceeding with low diskspace. Problems might occur!")));
1546 switch(m_settings->compressionEncoder())
1548 case SettingsModel::MP3Encoder:
1549 case SettingsModel::VorbisEncoder:
1550 case SettingsModel::AACEncoder:
1551 case SettingsModel::AC3Encoder:
1552 case SettingsModel::FLACEncoder:
1553 case SettingsModel::OpusEncoder:
1554 case SettingsModel::DCAEncoder:
1555 case SettingsModel::PCMEncoder:
1558 QMessageBox::warning(this, tr("LameXP"), tr("Sorry, an unsupported encoder has been chosen!"));
1559 ui->tabWidget->setCurrentIndex(3);
1563 if(!m_settings->outputToSourceDir())
1565 QFile writeTest(QString("%1/~%2.txt").arg(m_settings->outputDir(), lamexp_rand_str()));
1566 if(!(writeTest.open(QIODevice::ReadWrite) && (writeTest.write(writeTestBuffer) == strlen(writeTestBuffer))))
1568 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!")));
1569 ui->tabWidget->setCurrentIndex(1);
1586 void MainWindow::aboutButtonClicked(void)
1592 AboutDialog *aboutBox = new AboutDialog(m_settings, this);
1594 LAMEXP_DELETE(aboutBox);
1601 void MainWindow::closeButtonClicked(void)
1607 // =========================================================
1609 // =========================================================
1614 void MainWindow::tabPageChanged(int idx)
1618 QList<QAction*> actions = m_tabActionGroup->actions();
1619 for(int i = 0; i < actions.count(); i++)
1622 int actionIndex = actions.at(i)->data().toInt(&ok);
1623 if(ok && actionIndex == idx)
1625 actions.at(i)->setChecked(true);
1629 int initialWidth = this->width();
1630 int maximumWidth = QApplication::desktop()->availableGeometry().width();
1632 //Make sure all tab headers are fully visible
1633 if(this->isVisible())
1635 int delta = ui->tabWidget->sizeHint().width() - ui->tabWidget->width();
1638 this->resize(qMin(this->width() + delta, maximumWidth), this->height());
1642 //Tab specific operations
1643 if(idx == ui->tabWidget->indexOf(ui->tabOptions) && ui->scrollArea->widget() && this->isVisible())
1645 ui->scrollArea->widget()->updateGeometry();
1646 ui->scrollArea->viewport()->updateGeometry();
1647 qApp->processEvents();
1648 int delta = ui->scrollArea->widget()->width() - ui->scrollArea->viewport()->width();
1651 this->resize(qMin(this->width() + delta, maximumWidth), this->height());
1654 else if(idx == ui->tabWidget->indexOf(ui->tabSourceFiles))
1656 m_dropNoteLabel->setGeometry(0, 0, ui->sourceFileView->width(), ui->sourceFileView->height());
1658 else if(idx == ui->tabWidget->indexOf(ui->tabOutputDir))
1660 if(!m_fileSystemModel)
1662 QTimer::singleShot(125, this, SLOT(initOutputFolderModel()));
1666 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
1670 //Center window around previous position
1671 if(initialWidth < this->width())
1673 QPoint prevPos = this->pos();
1674 int delta = (this->width() - initialWidth) >> 2;
1675 move(prevPos.x() - delta, prevPos.y());
1680 * Tab action triggered
1682 void MainWindow::tabActionActivated(QAction *action)
1684 if(action && action->data().isValid())
1687 int index = action->data().toInt(&ok);
1690 ui->tabWidget->setCurrentIndex(index);
1695 // =========================================================
1697 // =========================================================
1700 * Style action triggered
1702 void MainWindow::styleActionActivated(QAction *action)
1704 //Change style setting
1705 if(action && action->data().isValid())
1708 int actionIndex = action->data().toInt(&ok);
1711 m_settings->interfaceStyle(actionIndex);
1715 //Set up the new style
1716 switch(m_settings->interfaceStyle())
1719 if(ui->actionStyleCleanlooks->isEnabled())
1721 ui->actionStyleCleanlooks->setChecked(true);
1722 QApplication::setStyle(new QCleanlooksStyle());
1726 if(ui->actionStyleWindowsVista->isEnabled())
1728 ui->actionStyleWindowsVista->setChecked(true);
1729 QApplication::setStyle(new QWindowsVistaStyle());
1733 if(ui->actionStyleWindowsXP->isEnabled())
1735 ui->actionStyleWindowsXP->setChecked(true);
1736 QApplication::setStyle(new QWindowsXPStyle());
1740 if(ui->actionStyleWindowsClassic->isEnabled())
1742 ui->actionStyleWindowsClassic->setChecked(true);
1743 QApplication::setStyle(new QWindowsStyle());
1747 ui->actionStylePlastique->setChecked(true);
1748 QApplication::setStyle(new QPlastiqueStyle());
1752 //Force re-translate after style change
1753 if(QEvent *e = new QEvent(QEvent::LanguageChange))
1760 const type_info &styleType = typeid(*qApp->style());
1761 const bool bTransparent = ((typeid(QWindowsVistaStyle) == styleType) || (typeid(QWindowsXPStyle) == styleType));
1762 MAKE_TRANSPARENT(ui->scrollArea, bTransparent);
1766 * Language action triggered
1768 void MainWindow::languageActionActivated(QAction *action)
1770 if(action->data().type() == QVariant::String)
1772 QString langId = action->data().toString();
1774 if(lamexp_install_translator(langId))
1776 action->setChecked(true);
1777 ui->actionLoadTranslationFromFile->setChecked(false);
1778 m_settings->currentLanguage(langId);
1779 m_settings->currentLanguageFile(QString());
1785 * Load language from file action triggered
1787 void MainWindow::languageFromFileActionActivated(bool checked)
1789 QFileDialog dialog(this, tr("Load Translation"));
1790 dialog.setFileMode(QFileDialog::ExistingFile);
1791 dialog.setNameFilter(QString("%1 (*.qm)").arg(tr("Translation Files")));
1795 QStringList selectedFiles = dialog.selectedFiles();
1796 const QString qmFile = QFileInfo(selectedFiles.first()).canonicalFilePath();
1797 if(lamexp_install_translator_from_file(qmFile))
1799 QList<QAction*> actions = m_languageActionGroup->actions();
1800 while(!actions.isEmpty())
1802 actions.takeFirst()->setChecked(false);
1804 ui->actionLoadTranslationFromFile->setChecked(true);
1805 m_settings->currentLanguageFile(qmFile);
1809 languageActionActivated(m_languageActionGroup->actions().first());
1814 // =========================================================
1816 // =========================================================
1819 * Disable update reminder action
1821 void MainWindow::disableUpdateReminderActionTriggered(bool checked)
1825 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))
1827 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!"))));
1828 m_settings->autoUpdateEnabled(false);
1832 m_settings->autoUpdateEnabled(true);
1837 QMessageBox::information(this, tr("Update Reminder"), NOBR(tr("The update reminder has been re-enabled.")));
1838 m_settings->autoUpdateEnabled(true);
1841 ui->actionDisableUpdateReminder->setChecked(!m_settings->autoUpdateEnabled());
1845 * Disable sound effects action
1847 void MainWindow::disableSoundsActionTriggered(bool checked)
1851 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))
1853 QMessageBox::information(this, tr("Sound Effects"), NOBR(tr("All sound effects have been disabled.")));
1854 m_settings->soundsEnabled(false);
1858 m_settings->soundsEnabled(true);
1863 QMessageBox::information(this, tr("Sound Effects"), NOBR(tr("The sound effects have been re-enabled.")));
1864 m_settings->soundsEnabled(true);
1867 ui->actionDisableSounds->setChecked(!m_settings->soundsEnabled());
1871 * Disable Nero AAC encoder action
1873 void MainWindow::disableNeroAacNotificationsActionTriggered(bool checked)
1877 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))
1879 QMessageBox::information(this, tr("Nero AAC Notifications"), NOBR(tr("All Nero AAC Encoder notifications have been disabled.")));
1880 m_settings->neroAacNotificationsEnabled(false);
1884 m_settings->neroAacNotificationsEnabled(true);
1889 QMessageBox::information(this, tr("Nero AAC Notifications"), NOBR(tr("The Nero AAC Encoder notifications have been re-enabled.")));
1890 m_settings->neroAacNotificationsEnabled(true);
1893 ui->actionDisableNeroAacNotifications->setChecked(!m_settings->neroAacNotificationsEnabled());
1897 * Disable slow startup action
1899 void MainWindow::disableSlowStartupNotificationsActionTriggered(bool checked)
1903 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))
1905 QMessageBox::information(this, tr("Slow Startup Notifications"), NOBR(tr("The slow startup notifications have been disabled.")));
1906 m_settings->antivirNotificationsEnabled(false);
1910 m_settings->antivirNotificationsEnabled(true);
1915 QMessageBox::information(this, tr("Slow Startup Notifications"), NOBR(tr("The slow startup notifications have been re-enabled.")));
1916 m_settings->antivirNotificationsEnabled(true);
1919 ui->actionDisableSlowStartupNotifications->setChecked(!m_settings->antivirNotificationsEnabled());
1923 * Import a Cue Sheet file
1925 void MainWindow::importCueSheetActionTriggered(bool checked)
1934 QString selectedCueFile;
1936 if(lamexp_themes_enabled())
1938 selectedCueFile = QFileDialog::getOpenFileName(this, tr("Open Cue Sheet"), m_settings->mostRecentInputPath(), QString("%1 (*.cue)").arg(tr("Cue Sheet File")));
1942 QFileDialog dialog(this, tr("Open Cue Sheet"));
1943 dialog.setFileMode(QFileDialog::ExistingFile);
1944 dialog.setNameFilter(QString("%1 (*.cue)").arg(tr("Cue Sheet File")));
1945 dialog.setDirectory(m_settings->mostRecentInputPath());
1948 selectedCueFile = dialog.selectedFiles().first();
1952 if(!selectedCueFile.isEmpty())
1954 m_settings->mostRecentInputPath(QFileInfo(selectedCueFile).canonicalPath());
1955 CueImportDialog *cueImporter = new CueImportDialog(this, m_fileListModel, selectedCueFile, m_settings);
1956 result = cueImporter->exec();
1957 LAMEXP_DELETE(cueImporter);
1960 if(result != (-1)) break;
1966 * Show the "drop box" widget
1968 void MainWindow::showDropBoxWidgetActionTriggered(bool checked)
1970 m_settings->dropBoxWidgetEnabled(true);
1972 if(!m_dropBox->isVisible())
1977 lamexp_blink_window(m_dropBox);
1981 * Check for beta (pre-release) updates
1983 void MainWindow::checkForBetaUpdatesActionTriggered(bool checked)
1985 bool checkUpdatesNow = false;
1989 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))
1991 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")))
1993 checkUpdatesNow = true;
1995 m_settings->autoUpdateCheckBeta(true);
1999 m_settings->autoUpdateCheckBeta(false);
2004 QMessageBox::information(this, tr("Beta Updates"), NOBR(tr("LameXP will <i>not</i> check for Beta (pre-release) updates from now on.")));
2005 m_settings->autoUpdateCheckBeta(false);
2008 ui->actionCheckForBetaUpdates->setChecked(m_settings->autoUpdateCheckBeta());
2012 if(checkForUpdates())
2014 QApplication::quit();
2020 * Hibernate computer action
2022 void MainWindow::hibernateComputerActionTriggered(bool checked)
2026 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))
2028 QMessageBox::information(this, tr("Hibernate Computer"), NOBR(tr("LameXP will hibernate the computer on shutdown from now on.")));
2029 m_settings->hibernateComputer(true);
2033 m_settings->hibernateComputer(false);
2038 QMessageBox::information(this, tr("Hibernate Computer"), NOBR(tr("LameXP will <i>not</i> hibernate the computer on shutdown from now on.")));
2039 m_settings->hibernateComputer(false);
2042 ui->actionHibernateComputer->setChecked(m_settings->hibernateComputer());
2046 * Disable shell integration action
2048 void MainWindow::disableShellIntegrationActionTriggered(bool checked)
2052 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))
2054 ShellIntegration::remove();
2055 QMessageBox::information(this, tr("Shell Integration"), NOBR(tr("The LameXP shell integration has been disabled.")));
2056 m_settings->shellIntegrationEnabled(false);
2060 m_settings->shellIntegrationEnabled(true);
2065 ShellIntegration::install();
2066 QMessageBox::information(this, tr("Shell Integration"), NOBR(tr("The LameXP shell integration has been re-enabled.")));
2067 m_settings->shellIntegrationEnabled(true);
2070 ui->actionDisableShellIntegration->setChecked(!m_settings->shellIntegrationEnabled());
2072 if(lamexp_portable_mode() && ui->actionDisableShellIntegration->isChecked())
2074 ui->actionDisableShellIntegration->setEnabled(false);
2078 // =========================================================
2080 // =========================================================
2083 * Visit homepage action
2085 void MainWindow::visitHomepageActionActivated(void)
2087 if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
2089 if(action->data().isValid() && (action->data().type() == QVariant::String))
2091 QDesktopServices::openUrl(QUrl(action->data().toString()));
2099 void MainWindow::documentActionActivated(void)
2101 if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
2103 if(action->data().isValid() && (action->data().type() == QVariant::String))
2105 QFileInfo document(action->data().toString());
2106 QFileInfo resource(QString(":/doc/%1.html").arg(document.baseName()));
2107 if(document.exists() && document.isFile() && (document.size() == resource.size()))
2109 QDesktopServices::openUrl(QUrl::fromLocalFile(document.canonicalFilePath()));
2113 QFile source(resource.filePath());
2114 QFile output(QString("%1/%2.%3.html").arg(lamexp_temp_folder2(), document.baseName(), lamexp_rand_str().left(8)));
2115 if(source.open(QIODevice::ReadOnly) && output.open(QIODevice::ReadWrite))
2117 output.write(source.readAll());
2118 action->setData(output.fileName());
2121 QDesktopServices::openUrl(QUrl::fromLocalFile(output.fileName()));
2129 * Check for updates action
2131 void MainWindow::checkUpdatesActionActivated(void)
2138 bFlag = checkForUpdates();
2143 QApplication::quit();
2147 // =========================================================
2148 // Source file slots
2149 // =========================================================
2152 * Add file(s) button
2154 void MainWindow::addFilesButtonClicked(void)
2160 if(lamexp_themes_enabled())
2162 QStringList fileTypeFilters = DecoderRegistry::getSupportedTypes();
2163 QStringList selectedFiles = QFileDialog::getOpenFileNames(this, tr("Add file(s)"), m_settings->mostRecentInputPath(), fileTypeFilters.join(";;"));
2164 if(!selectedFiles.isEmpty())
2166 m_settings->mostRecentInputPath(QFileInfo(selectedFiles.first()).canonicalPath());
2167 addFiles(selectedFiles);
2172 QFileDialog dialog(this, tr("Add file(s)"));
2173 QStringList fileTypeFilters = DecoderRegistry::getSupportedTypes();
2174 dialog.setFileMode(QFileDialog::ExistingFiles);
2175 dialog.setNameFilter(fileTypeFilters.join(";;"));
2176 dialog.setDirectory(m_settings->mostRecentInputPath());
2179 QStringList selectedFiles = dialog.selectedFiles();
2180 if(!selectedFiles.isEmpty())
2182 m_settings->mostRecentInputPath(QFileInfo(selectedFiles.first()).canonicalPath());
2183 addFiles(selectedFiles);
2191 * Open folder action
2193 void MainWindow::openFolderActionActivated(void)
2196 QString selectedFolder;
2198 if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
2202 if(lamexp_themes_enabled())
2204 selectedFolder = QFileDialog::getExistingDirectory(this, tr("Add Folder"), m_settings->mostRecentInputPath());
2208 QFileDialog dialog(this, tr("Add Folder"));
2209 dialog.setFileMode(QFileDialog::DirectoryOnly);
2210 dialog.setDirectory(m_settings->mostRecentInputPath());
2213 selectedFolder = dialog.selectedFiles().first();
2217 if(!selectedFolder.isEmpty())
2219 m_settings->mostRecentInputPath(QDir(selectedFolder).canonicalPath());
2220 addFolder(selectedFolder, action->data().toBool());
2227 * Remove file button
2229 void MainWindow::removeFileButtonClicked(void)
2231 if(ui->sourceFileView->currentIndex().isValid())
2233 int iRow = ui->sourceFileView->currentIndex().row();
2234 m_fileListModel->removeFile(ui->sourceFileView->currentIndex());
2235 ui->sourceFileView->selectRow(iRow < m_fileListModel->rowCount() ? iRow : m_fileListModel->rowCount()-1);
2240 * Clear files button
2242 void MainWindow::clearFilesButtonClicked(void)
2244 m_fileListModel->clearFiles();
2248 * Move file up button
2250 void MainWindow::fileUpButtonClicked(void)
2252 if(ui->sourceFileView->currentIndex().isValid())
2254 int iRow = ui->sourceFileView->currentIndex().row() - 1;
2255 m_fileListModel->moveFile(ui->sourceFileView->currentIndex(), -1);
2256 ui->sourceFileView->selectRow(iRow >= 0 ? iRow : 0);
2261 * Move file down button
2263 void MainWindow::fileDownButtonClicked(void)
2265 if(ui->sourceFileView->currentIndex().isValid())
2267 int iRow = ui->sourceFileView->currentIndex().row() + 1;
2268 m_fileListModel->moveFile(ui->sourceFileView->currentIndex(), 1);
2269 ui->sourceFileView->selectRow(iRow < m_fileListModel->rowCount() ? iRow : m_fileListModel->rowCount()-1);
2274 * Show details button
2276 void MainWindow::showDetailsButtonClicked(void)
2281 MetaInfoDialog *metaInfoDialog = new MetaInfoDialog(this);
2282 QModelIndex index = ui->sourceFileView->currentIndex();
2284 while(index.isValid())
2288 index = m_fileListModel->index(index.row() + 1, index.column());
2289 ui->sourceFileView->selectRow(index.row());
2293 index = m_fileListModel->index(index.row() - 1, index.column());
2294 ui->sourceFileView->selectRow(index.row());
2297 AudioFileModel &file = (*m_fileListModel)[index];
2300 iResult = metaInfoDialog->exec(file, index.row() > 0, index.row() < m_fileListModel->rowCount() - 1);
2303 if(iResult == INT_MAX)
2305 m_metaInfoModel->assignInfoFrom(file);
2306 ui->tabWidget->setCurrentIndex(ui->tabWidget->indexOf(ui->tabMetaData));
2313 LAMEXP_DELETE(metaInfoDialog);
2314 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
2315 sourceFilesScrollbarMoved(0);
2319 * Show context menu for source files
2321 void MainWindow::sourceFilesContextMenu(const QPoint &pos)
2323 QAbstractScrollArea *scrollArea = dynamic_cast<QAbstractScrollArea*>(QObject::sender());
2324 QWidget *sender = scrollArea ? scrollArea->viewport() : dynamic_cast<QWidget*>(QObject::sender());
2328 if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0)
2330 m_sourceFilesContextMenu->popup(sender->mapToGlobal(pos));
2336 * Scrollbar of source files moved
2338 void MainWindow::sourceFilesScrollbarMoved(int)
2340 ui->sourceFileView->resizeColumnToContents(0);
2344 * Open selected file in external player
2346 void MainWindow::previewContextActionTriggered(void)
2348 const static wchar_t *registryPrefix[2] = { L"SOFTWARE\\", L"SOFTWARE\\Wow6432Node\\" };
2349 const static wchar_t *registryKeys[3] =
2351 L"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{97D341C8-B0D1-4E4A-A49A-C30B52F168E9}",
2352 L"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{DB9E4EAB-2717-499F-8D56-4CC8A644AB60}",
2355 const static wchar_t *appNames[4] = { L"smplayer_portable.exe", L"smplayer.exe", L"MPUI.exe", L"foobar2000.exe" };
2356 const static wchar_t *valueNames[2] = { L"InstallLocation", L"InstallDir" };
2358 QModelIndex index = ui->sourceFileView->currentIndex();
2359 if(!index.isValid())
2364 for(size_t i = 0; i < 3; i++)
2366 for(size_t j = 0; j < 2; j++)
2368 QString mplayerPath;
2369 HKEY registryKeyHandle = NULL;
2371 const QString currentKey = WCHAR2QSTR(registryPrefix[j]).append(WCHAR2QSTR(registryKeys[i]));
2372 if(RegOpenKeyExW(HKEY_LOCAL_MACHINE, QWCHAR(currentKey), 0, KEY_READ, ®istryKeyHandle) == ERROR_SUCCESS)
2374 for(size_t k = 0; k < 2; k++)
2376 wchar_t Buffer[4096];
2377 DWORD BuffSize = sizeof(wchar_t*) * 4096;
2378 DWORD DataType = REG_NONE;
2379 if(RegQueryValueExW(registryKeyHandle, valueNames[k], 0, &DataType, reinterpret_cast<BYTE*>(Buffer), &BuffSize) == ERROR_SUCCESS)
2381 if((DataType == REG_SZ) || (DataType == REG_EXPAND_SZ) || (DataType == REG_LINK))
2383 mplayerPath = WCHAR2QSTR(Buffer);
2388 RegCloseKey(registryKeyHandle);
2391 if(!mplayerPath.isEmpty())
2393 QDir mplayerDir(mplayerPath);
2394 if(mplayerDir.exists())
2396 for(size_t k = 0; k < 4; k++)
2398 if(mplayerDir.exists(WCHAR2QSTR(appNames[k])))
2400 qDebug("Player found at:\n%s\n", mplayerDir.absoluteFilePath(WCHAR2QSTR(appNames[k])).toUtf8().constData());
2401 QProcess::startDetached(mplayerDir.absoluteFilePath(WCHAR2QSTR(appNames[k])), QStringList() << QDir::toNativeSeparators(m_fileListModel->getFile(index).filePath()));
2410 qDebug("Player not found, falling back to default application...");
2411 QDesktopServices::openUrl(QString("file:///").append(m_fileListModel->getFile(index).filePath()));
2415 * Find selected file in explorer
2417 void MainWindow::findFileContextActionTriggered(void)
2419 QModelIndex index = ui->sourceFileView->currentIndex();
2422 QString systemRootPath;
2424 QDir systemRoot(lamexp_known_folder(lamexp_folder_systemfolder));
2425 if(systemRoot.exists() && systemRoot.cdUp())
2427 systemRootPath = systemRoot.canonicalPath();
2430 if(!systemRootPath.isEmpty())
2432 QFileInfo explorer(QString("%1/explorer.exe").arg(systemRootPath));
2433 if(explorer.exists() && explorer.isFile())
2435 QProcess::execute(explorer.canonicalFilePath(), QStringList() << "/select," << QDir::toNativeSeparators(m_fileListModel->getFile(index).filePath()));
2441 qWarning("SystemRoot directory could not be detected!");
2447 * Add all pending files
2449 void MainWindow::handleDelayedFiles(void)
2451 m_delayedFileTimer->stop();
2453 if(m_delayedFileList->isEmpty())
2458 if(m_banner->isVisible())
2460 m_delayedFileTimer->start(5000);
2464 QStringList selectedFiles;
2465 ui->tabWidget->setCurrentIndex(0);
2467 while(!m_delayedFileList->isEmpty())
2469 QFileInfo currentFile = QFileInfo(m_delayedFileList->takeFirst());
2470 if(!currentFile.exists() || !currentFile.isFile())
2474 selectedFiles << currentFile.canonicalFilePath();
2477 addFiles(selectedFiles);
2481 * Export Meta tags to CSV file
2483 void MainWindow::exportCsvContextActionTriggered(void)
2487 QString selectedCsvFile;
2489 if(lamexp_themes_enabled())
2491 selectedCsvFile = QFileDialog::getSaveFileName(this, tr("Save CSV file"), m_settings->mostRecentInputPath(), QString("%1 (*.csv)").arg(tr("CSV File")));
2495 QFileDialog dialog(this, tr("Save CSV file"));
2496 dialog.setFileMode(QFileDialog::AnyFile);
2497 dialog.setAcceptMode(QFileDialog::AcceptSave);
2498 dialog.setNameFilter(QString("%1 (*.csv)").arg(tr("CSV File")));
2499 dialog.setDirectory(m_settings->mostRecentInputPath());
2502 selectedCsvFile = dialog.selectedFiles().first();
2506 if(!selectedCsvFile.isEmpty())
2508 m_settings->mostRecentInputPath(QFileInfo(selectedCsvFile).canonicalPath());
2509 switch(m_fileListModel->exportToCsv(selectedCsvFile))
2511 case FileListModel::CsvError_NoTags:
2512 QMessageBox::critical(this, tr("CSV Export"), NOBR(tr("Sorry, there are no meta tags that can be exported!")));
2514 case FileListModel::CsvError_FileOpen:
2515 QMessageBox::critical(this, tr("CSV Export"), NOBR(tr("Sorry, failed to open CSV file for writing!")));
2517 case FileListModel::CsvError_FileWrite:
2518 QMessageBox::critical(this, tr("CSV Export"), NOBR(tr("Sorry, failed to write to the CSV file!")));
2520 case FileListModel::CsvError_OK:
2521 QMessageBox::information(this, tr("CSV Export"), NOBR(tr("The CSV files was created successfully!")));
2524 qWarning("exportToCsv: Unknown return code!");
2532 * Import Meta tags from CSV file
2534 void MainWindow::importCsvContextActionTriggered(void)
2538 QString selectedCsvFile;
2540 if(lamexp_themes_enabled())
2542 selectedCsvFile = QFileDialog::getOpenFileName(this, tr("Open CSV file"), m_settings->mostRecentInputPath(), QString("%1 (*.csv)").arg(tr("CSV File")));
2546 QFileDialog dialog(this, tr("Open CSV file"));
2547 dialog.setFileMode(QFileDialog::ExistingFile);
2548 dialog.setNameFilter(QString("%1 (*.csv)").arg(tr("CSV File")));
2549 dialog.setDirectory(m_settings->mostRecentInputPath());
2552 selectedCsvFile = dialog.selectedFiles().first();
2556 if(!selectedCsvFile.isEmpty())
2558 m_settings->mostRecentInputPath(QFileInfo(selectedCsvFile).canonicalPath());
2559 switch(m_fileListModel->importFromCsv(this, selectedCsvFile))
2561 case FileListModel::CsvError_FileOpen:
2562 QMessageBox::critical(this, tr("CSV Import"), NOBR(tr("Sorry, failed to open CSV file for reading!")));
2564 case FileListModel::CsvError_FileRead:
2565 QMessageBox::critical(this, tr("CSV Import"), NOBR(tr("Sorry, failed to read from the CSV file!")));
2567 case FileListModel::CsvError_NoTags:
2568 QMessageBox::critical(this, tr("CSV Import"), NOBR(tr("Sorry, the CSV file does not contain any known fields!")));
2570 case FileListModel::CsvError_Incomplete:
2571 QMessageBox::warning(this, tr("CSV Import"), NOBR(tr("CSV file is incomplete. Not all files were updated!")));
2573 case FileListModel::CsvError_OK:
2574 QMessageBox::information(this, tr("CSV Import"), NOBR(tr("The CSV files was imported successfully!")));
2576 case FileListModel::CsvError_Aborted:
2577 /* User aborted, ignore! */
2580 qWarning("exportToCsv: Unknown return code!");
2587 * Show or hide Drag'n'Drop notice after model reset
2589 void MainWindow::sourceModelChanged(void)
2591 m_dropNoteLabel->setVisible(m_fileListModel->rowCount() <= 0);
2594 // =========================================================
2595 // Output folder slots
2596 // =========================================================
2599 * Output folder changed (mouse clicked)
2601 void MainWindow::outputFolderViewClicked(const QModelIndex &index)
2603 if(index.isValid() && (ui->outputFolderView->currentIndex() != index))
2605 ui->outputFolderView->setCurrentIndex(index);
2608 if(m_fileSystemModel && index.isValid())
2610 QString selectedDir = m_fileSystemModel->filePath(index);
2611 if(selectedDir.length() < 3) selectedDir.append(QDir::separator());
2612 ui->outputFolderLabel->setText(QDir::toNativeSeparators(selectedDir));
2613 ui->outputFolderLabel->setToolTip(ui->outputFolderLabel->text());
2614 m_settings->outputDir(selectedDir);
2618 ui->outputFolderLabel->setText(QDir::toNativeSeparators(m_settings->outputDir()));
2619 ui->outputFolderLabel->setToolTip(ui->outputFolderLabel->text());
2624 * Output folder changed (mouse moved)
2626 void MainWindow::outputFolderViewMoved(const QModelIndex &index)
2628 if(QApplication::mouseButtons() & Qt::LeftButton)
2630 outputFolderViewClicked(index);
2635 * Goto desktop button
2637 void MainWindow::gotoDesktopButtonClicked(void)
2639 if(!m_fileSystemModel)
2641 qWarning("File system model not initialized yet!");
2645 QString desktopPath = QDesktopServices::storageLocation(QDesktopServices::DesktopLocation);
2647 if(!desktopPath.isEmpty() && QDir(desktopPath).exists())
2649 ui->outputFolderView->setCurrentIndex(m_fileSystemModel->index(desktopPath));
2650 outputFolderViewClicked(ui->outputFolderView->currentIndex());
2651 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2655 ui->buttonGotoDesktop->setEnabled(false);
2660 * Goto home folder button
2662 void MainWindow::gotoHomeFolderButtonClicked(void)
2664 if(!m_fileSystemModel)
2666 qWarning("File system model not initialized yet!");
2670 QString homePath = QDesktopServices::storageLocation(QDesktopServices::HomeLocation);
2672 if(!homePath.isEmpty() && QDir(homePath).exists())
2674 ui->outputFolderView->setCurrentIndex(m_fileSystemModel->index(homePath));
2675 outputFolderViewClicked(ui->outputFolderView->currentIndex());
2676 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2680 ui->buttonGotoHome->setEnabled(false);
2685 * Goto music folder button
2687 void MainWindow::gotoMusicFolderButtonClicked(void)
2689 if(!m_fileSystemModel)
2691 qWarning("File system model not initialized yet!");
2695 QString musicPath = QDesktopServices::storageLocation(QDesktopServices::MusicLocation);
2697 if(!musicPath.isEmpty() && QDir(musicPath).exists())
2699 ui->outputFolderView->setCurrentIndex(m_fileSystemModel->index(musicPath));
2700 outputFolderViewClicked(ui->outputFolderView->currentIndex());
2701 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2705 ui->buttonGotoMusic->setEnabled(false);
2710 * Goto music favorite output folder
2712 void MainWindow::gotoFavoriteFolder(void)
2714 if(!m_fileSystemModel)
2716 qWarning("File system model not initialized yet!");
2720 QAction *item = dynamic_cast<QAction*>(QObject::sender());
2724 QDir path(item->data().toString());
2727 ui->outputFolderView->setCurrentIndex(m_fileSystemModel->index(path.canonicalPath()));
2728 outputFolderViewClicked(ui->outputFolderView->currentIndex());
2729 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2733 MessageBeep(MB_ICONERROR);
2734 m_outputFolderFavoritesMenu->removeAction(item);
2735 item->deleteLater();
2741 * Make folder button
2743 void MainWindow::makeFolderButtonClicked(void)
2747 if(!m_fileSystemModel)
2749 qWarning("File system model not initialized yet!");
2753 QDir basePath(m_fileSystemModel->fileInfo(ui->outputFolderView->currentIndex()).absoluteFilePath());
2754 QString suggestedName = tr("New Folder");
2756 if(!m_metaData->fileArtist().isEmpty() && !m_metaData->fileAlbum().isEmpty())
2758 suggestedName = QString("%1 - %2").arg(m_metaData->fileArtist(), m_metaData->fileAlbum());
2760 else if(!m_metaData->fileArtist().isEmpty())
2762 suggestedName = m_metaData->fileArtist();
2764 else if(!m_metaData->fileAlbum().isEmpty())
2766 suggestedName = m_metaData->fileAlbum();
2770 for(int i = 0; i < m_fileListModel->rowCount(); i++)
2772 AudioFileModel audioFile = m_fileListModel->getFile(m_fileListModel->index(i, 0));
2773 if(!audioFile.fileAlbum().isEmpty() || !audioFile.fileArtist().isEmpty())
2775 if(!audioFile.fileArtist().isEmpty() && !audioFile.fileAlbum().isEmpty())
2777 suggestedName = QString("%1 - %2").arg(audioFile.fileArtist(), audioFile.fileAlbum());
2779 else if(!audioFile.fileArtist().isEmpty())
2781 suggestedName = audioFile.fileArtist();
2783 else if(!audioFile.fileAlbum().isEmpty())
2785 suggestedName = audioFile.fileAlbum();
2792 suggestedName = lamexp_clean_filename(suggestedName);
2796 bool bApplied = false;
2797 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();
2801 folderName = lamexp_clean_filepath(folderName.simplified());
2803 if(folderName.isEmpty())
2805 MessageBeep(MB_ICONERROR);
2810 QString newFolder = folderName;
2812 while(basePath.exists(newFolder))
2814 newFolder = QString(folderName).append(QString().sprintf(" (%d)", ++i));
2817 if(basePath.mkpath(newFolder))
2819 QDir createdDir = basePath;
2820 if(createdDir.cd(newFolder))
2822 QModelIndex newIndex = m_fileSystemModel->index(createdDir.canonicalPath());
2823 ui->outputFolderView->setCurrentIndex(newIndex);
2824 outputFolderViewClicked(newIndex);
2825 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2830 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!")));
2838 * Output to source dir changed
2840 void MainWindow::saveToSourceFolderChanged(void)
2842 m_settings->outputToSourceDir(ui->saveToSourceFolderCheckBox->isChecked());
2846 * Prepend relative source file path to output file name changed
2848 void MainWindow::prependRelativePathChanged(void)
2850 m_settings->prependRelativeSourcePath(ui->prependRelativePathCheckBox->isChecked());
2854 * Show context menu for output folder
2856 void MainWindow::outputFolderContextMenu(const QPoint &pos)
2858 QAbstractScrollArea *scrollArea = dynamic_cast<QAbstractScrollArea*>(QObject::sender());
2859 QWidget *sender = scrollArea ? scrollArea->viewport() : dynamic_cast<QWidget*>(QObject::sender());
2861 if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0)
2863 m_outputFolderContextMenu->popup(sender->mapToGlobal(pos));
2868 * Show selected folder in explorer
2870 void MainWindow::showFolderContextActionTriggered(void)
2872 if(!m_fileSystemModel)
2874 qWarning("File system model not initialized yet!");
2878 QString path = QDir::toNativeSeparators(m_fileSystemModel->filePath(ui->outputFolderView->currentIndex()));
2879 if(!path.endsWith(QDir::separator())) path.append(QDir::separator());
2880 ShellExecuteW(reinterpret_cast<HWND>(this->winId()), L"explore", QWCHAR(path), NULL, NULL, SW_SHOW);
2884 * Refresh the directory outline
2886 void MainWindow::refreshFolderContextActionTriggered(void)
2888 //force re-initialization
2889 QTimer::singleShot(0, this, SLOT(initOutputFolderModel()));
2893 * Go one directory up
2895 void MainWindow::goUpFolderContextActionTriggered(void)
2897 QModelIndex current = ui->outputFolderView->currentIndex();
2898 if(current.isValid())
2900 QModelIndex parent = current.parent();
2901 if(parent.isValid())
2904 ui->outputFolderView->setCurrentIndex(parent);
2905 outputFolderViewClicked(parent);
2909 MessageBeep(MB_ICONWARNING);
2911 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2916 * Add current folder to favorites
2918 void MainWindow::addFavoriteFolderActionTriggered(void)
2920 QString path = m_fileSystemModel->filePath(ui->outputFolderView->currentIndex());
2921 QStringList favorites = m_settings->favoriteOutputFolders().split("|", QString::SkipEmptyParts);
2923 if(!favorites.contains(path, Qt::CaseInsensitive))
2925 favorites.append(path);
2926 while(favorites.count() > 6) favorites.removeFirst();
2930 MessageBeep(MB_ICONWARNING);
2933 m_settings->favoriteOutputFolders(favorites.join("|"));
2938 * Output folder edit finished
2940 void MainWindow::outputFolderEditFinished(void)
2942 if(ui->outputFolderEdit->isHidden())
2944 return; //Not currently in edit mode!
2949 QString text = QDir::fromNativeSeparators(ui->outputFolderEdit->text().trimmed());
2950 while(text.startsWith('"') || text.startsWith('/')) text = text.right(text.length() - 1).trimmed();
2951 while(text.endsWith('"') || text.endsWith('/')) text = text.left(text.length() - 1).trimmed();
2953 static const char *str = "?*<>|\"";
2954 for(size_t i = 0; str[i]; i++) text.replace(str[i], "_");
2956 if(!((text.length() >= 2) && text.at(0).isLetter() && text.at(1) == QChar(':')))
2958 text = QString("%1/%2").arg(QDir::fromNativeSeparators(ui->outputFolderLabel->text()), text);
2961 if(text.length() == 2) text += "/"; /* "X:" => "X:/" */
2963 while(text.length() > 2)
2965 QFileInfo info(text);
2966 if(info.exists() && info.isDir())
2968 QModelIndex index = m_fileSystemModel->index(QFileInfo(info.canonicalFilePath()).absoluteFilePath());
2972 ui->outputFolderView->setCurrentIndex(index);
2973 outputFolderViewClicked(index);
2977 else if(info.exists() && info.isFile())
2979 QModelIndex index = m_fileSystemModel->index(QFileInfo(info.canonicalPath()).absoluteFilePath());
2983 ui->outputFolderView->setCurrentIndex(index);
2984 outputFolderViewClicked(index);
2989 text = text.left(text.length() - 1).trimmed();
2992 ui->outputFolderEdit->setVisible(false);
2993 ui->outputFolderLabel->setVisible(true);
2994 ui->outputFolderView->setEnabled(true);
2996 if(!ok) MessageBeep(MB_ICONERROR);
2997 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
3001 * Initialize file system model
3003 void MainWindow::initOutputFolderModel(void)
3005 if(m_outputFolderNoteBox->isHidden())
3007 m_outputFolderNoteBox->show();
3008 m_outputFolderNoteBox->repaint();
3009 m_outputFolderViewInitCounter = 4;
3011 if(m_fileSystemModel)
3013 SET_MODEL(ui->outputFolderView, NULL);
3014 LAMEXP_DELETE(m_fileSystemModel);
3015 ui->outputFolderView->repaint();
3018 if(m_fileSystemModel = new QFileSystemModelEx())
3020 m_fileSystemModel->installEventFilter(this);
3021 connect(m_fileSystemModel, SIGNAL(directoryLoaded(QString)), this, SLOT(outputFolderDirectoryLoaded(QString)));
3022 connect(m_fileSystemModel, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(outputFolderRowsInserted(QModelIndex,int,int)));
3024 SET_MODEL(ui->outputFolderView, m_fileSystemModel);
3025 ui->outputFolderView->header()->setStretchLastSection(true);
3026 ui->outputFolderView->header()->hideSection(1);
3027 ui->outputFolderView->header()->hideSection(2);
3028 ui->outputFolderView->header()->hideSection(3);
3030 m_fileSystemModel->setRootPath("");
3031 QModelIndex index = m_fileSystemModel->index(m_settings->outputDir());
3032 if(index.isValid()) ui->outputFolderView->setCurrentIndex(index);
3033 outputFolderViewClicked(ui->outputFolderView->currentIndex());
3036 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
3037 QTimer::singleShot(125, this, SLOT(initOutputFolderModel_doAsync()));
3042 * Initialize file system model (do NOT call this one directly!)
3044 void MainWindow::initOutputFolderModel_doAsync(void)
3046 if(m_outputFolderViewInitCounter > 0)
3048 m_outputFolderViewInitCounter--;
3049 QTimer::singleShot(125, this, SLOT(initOutputFolderModel_doAsync()));
3053 QTimer::singleShot(125, m_outputFolderNoteBox, SLOT(hide()));
3054 ui->outputFolderView->setFocus();
3059 * Center current folder in view
3061 void MainWindow::centerOutputFolderModel(void)
3063 if(ui->outputFolderView->isVisible())
3065 centerOutputFolderModel_doAsync();
3066 QTimer::singleShot(125, this, SLOT(centerOutputFolderModel_doAsync()));
3071 * Center current folder in view (do NOT call this one directly!)
3073 void MainWindow::centerOutputFolderModel_doAsync(void)
3075 if(ui->outputFolderView->isVisible())
3077 m_outputFolderViewCentering = true;
3078 const QModelIndex index = ui->outputFolderView->currentIndex();
3079 ui->outputFolderView->scrollTo(index, QAbstractItemView::PositionAtCenter);
3080 ui->outputFolderView->setFocus();
3085 * File system model asynchronously loaded a dir
3087 void MainWindow::outputFolderDirectoryLoaded(const QString &path)
3089 if(m_outputFolderViewCentering)
3091 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
3096 * File system model inserted new items
3098 void MainWindow::outputFolderRowsInserted(const QModelIndex &parent, int start, int end)
3100 if(m_outputFolderViewCentering)
3102 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
3107 * Directory view item was expanded by user
3109 void MainWindow::outputFolderItemExpanded(const QModelIndex &item)
3111 //We need to stop centering as soon as the user has expanded an item manually!
3112 m_outputFolderViewCentering = false;
3116 * View event for output folder control occurred
3118 void MainWindow::outputFolderViewEventOccurred(QWidget *sender, QEvent *event)
3120 switch(event->type())
3124 case QEvent::KeyPress:
3125 case QEvent::KeyRelease:
3126 case QEvent::FocusIn:
3127 case QEvent::FocusOut:
3128 case QEvent::TouchEnd:
3129 outputFolderViewClicked(ui->outputFolderView->currentIndex());
3135 * Mouse event for output folder control occurred
3137 void MainWindow::outputFolderMouseEventOccurred(QWidget *sender, QEvent *event)
3139 QMouseEvent *mouseEvent = dynamic_cast<QMouseEvent*>(event);
3140 QPoint pos = (mouseEvent) ? mouseEvent->pos() : QPoint();
3142 if(sender == ui->outputFolderLabel)
3144 switch(event->type())
3146 case QEvent::MouseButtonPress:
3147 if(mouseEvent && (mouseEvent->button() == Qt::LeftButton))
3149 QString path = ui->outputFolderLabel->text();
3150 if(!path.endsWith(QDir::separator())) path.append(QDir::separator());
3151 ShellExecuteW(reinterpret_cast<HWND>(this->winId()), L"explore", QWCHAR(path), NULL, NULL, SW_SHOW);
3155 ui->outputFolderLabel->setForegroundRole(QPalette::Link);
3158 ui->outputFolderLabel->setForegroundRole(QPalette::WindowText);
3163 if((sender == ui->outputFoldersFovoritesLabel) || (sender == ui->outputFoldersEditorLabel) || (sender == ui->outputFoldersGoUpLabel))
3165 const type_info &styleType = typeid(*qApp->style());
3166 if((typeid(QPlastiqueStyle) == styleType) || (typeid(QWindowsStyle) == styleType))
3168 switch(event->type())
3171 dynamic_cast<QLabel*>(sender)->setFrameShadow(ui->outputFolderView->isEnabled() ? QFrame::Raised : QFrame::Plain);
3173 case QEvent::MouseButtonPress:
3174 dynamic_cast<QLabel*>(sender)->setFrameShadow(ui->outputFolderView->isEnabled() ? QFrame::Sunken : QFrame::Plain);
3176 case QEvent::MouseButtonRelease:
3177 dynamic_cast<QLabel*>(sender)->setFrameShadow(ui->outputFolderView->isEnabled() ? QFrame::Raised : QFrame::Plain);
3180 dynamic_cast<QLabel*>(sender)->setFrameShadow(ui->outputFolderView->isEnabled() ? QFrame::Plain : QFrame::Plain);
3186 dynamic_cast<QLabel*>(sender)->setFrameShadow(QFrame::Plain);
3189 if((event->type() == QEvent::MouseButtonRelease) && ui->outputFolderView->isEnabled() && (mouseEvent))
3191 if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0 && mouseEvent->button() != Qt::MidButton)
3193 if(sender == ui->outputFoldersFovoritesLabel)
3195 m_outputFolderFavoritesMenu->popup(sender->mapToGlobal(pos));
3197 else if(sender == ui->outputFoldersEditorLabel)
3199 ui->outputFolderView->setEnabled(false);
3200 ui->outputFolderLabel->setVisible(false);
3201 ui->outputFolderEdit->setVisible(true);
3202 ui->outputFolderEdit->setText(ui->outputFolderLabel->text());
3203 ui->outputFolderEdit->selectAll();
3204 ui->outputFolderEdit->setFocus();
3206 else if(sender == ui->outputFoldersGoUpLabel)
3208 QTimer::singleShot(0, this, SLOT(goUpFolderContextActionTriggered()));
3212 throw "Oups, this is not supposed to happen!";
3219 // =========================================================
3220 // Metadata tab slots
3221 // =========================================================
3224 * Edit meta button clicked
3226 void MainWindow::editMetaButtonClicked(void)
3230 const QModelIndex index = ui->metaDataView->currentIndex();
3234 m_metaInfoModel->editItem(index, this);
3236 if(index.row() == 4)
3238 m_settings->metaInfoPosition(m_metaData->filePosition());
3244 * Reset meta button clicked
3246 void MainWindow::clearMetaButtonClicked(void)
3249 m_metaInfoModel->clearData();
3253 * Meta tags enabled changed
3255 void MainWindow::metaTagsEnabledChanged(void)
3257 m_settings->writeMetaTags(ui->writeMetaDataCheckBox->isChecked());
3261 * Playlist enabled changed
3263 void MainWindow::playlistEnabledChanged(void)
3265 m_settings->createPlaylist(ui->generatePlaylistCheckBox->isChecked());
3268 // =========================================================
3269 // Compression tab slots
3270 // =========================================================
3275 void MainWindow::updateEncoder(int id)
3277 m_settings->compressionEncoder(id);
3279 switch(m_settings->compressionEncoder())
3281 case SettingsModel::VorbisEncoder:
3282 ui->radioButtonModeQuality->setEnabled(true);
3283 ui->radioButtonModeAverageBitrate->setEnabled(true);
3284 ui->radioButtonConstBitrate->setEnabled(false);
3285 if(ui->radioButtonConstBitrate->isChecked()) ui->radioButtonModeQuality->setChecked(true);
3286 ui->sliderBitrate->setEnabled(true);
3288 case SettingsModel::AC3Encoder:
3289 ui->radioButtonModeQuality->setEnabled(true);
3290 ui->radioButtonModeQuality->setChecked(true);
3291 ui->radioButtonModeAverageBitrate->setEnabled(false);
3292 ui->radioButtonConstBitrate->setEnabled(true);
3293 ui->sliderBitrate->setEnabled(true);
3295 case SettingsModel::FLACEncoder:
3296 ui->radioButtonModeQuality->setEnabled(false);
3297 ui->radioButtonModeQuality->setChecked(true);
3298 ui->radioButtonModeAverageBitrate->setEnabled(false);
3299 ui->radioButtonConstBitrate->setEnabled(false);
3300 ui->sliderBitrate->setEnabled(true);
3302 case SettingsModel::PCMEncoder:
3303 ui->radioButtonModeQuality->setEnabled(false);
3304 ui->radioButtonModeQuality->setChecked(true);
3305 ui->radioButtonModeAverageBitrate->setEnabled(false);
3306 ui->radioButtonConstBitrate->setEnabled(false);
3307 ui->sliderBitrate->setEnabled(false);
3309 case SettingsModel::AACEncoder:
3310 ui->radioButtonModeQuality->setEnabled(true);
3311 ui->radioButtonModeAverageBitrate->setEnabled(!m_fhgEncoderAvailable);
3312 if(m_fhgEncoderAvailable && ui->radioButtonModeAverageBitrate->isChecked()) ui->radioButtonConstBitrate->setChecked(true);
3313 ui->radioButtonConstBitrate->setEnabled(true);
3314 ui->sliderBitrate->setEnabled(true);
3316 case SettingsModel::DCAEncoder:
3317 ui->radioButtonModeQuality->setEnabled(false);
3318 ui->radioButtonModeAverageBitrate->setEnabled(false);
3319 ui->radioButtonConstBitrate->setEnabled(true);
3320 ui->radioButtonConstBitrate->setChecked(true);
3321 ui->sliderBitrate->setEnabled(true);
3324 ui->radioButtonModeQuality->setEnabled(true);
3325 ui->radioButtonModeAverageBitrate->setEnabled(true);
3326 ui->radioButtonConstBitrate->setEnabled(true);
3327 ui->sliderBitrate->setEnabled(true);
3331 if(m_settings->compressionEncoder() == SettingsModel::AACEncoder)
3333 const QString encoderName = m_qaacEncoderAvailable ? tr("QAAC (Apple)") : (m_fhgEncoderAvailable ? tr("FHG AAC (Winamp)") : (m_neroEncoderAvailable ? tr("Nero AAC") : tr("Not available!")));
3334 ui->labelEncoderInfo->setVisible(true);
3335 ui->labelEncoderInfo->setText(tr("Current AAC Encoder: %1").arg(encoderName));
3339 ui->labelEncoderInfo->setVisible(false);
3342 updateRCMode(m_modeButtonGroup->checkedId());
3346 * Update rate-control mode
3348 void MainWindow::updateRCMode(int id)
3350 m_settings->compressionRCMode(id);
3352 switch(m_settings->compressionEncoder())
3354 case SettingsModel::MP3Encoder:
3355 switch(m_settings->compressionRCMode())
3357 case SettingsModel::VBRMode:
3358 ui->sliderBitrate->setMinimum(0);
3359 ui->sliderBitrate->setMaximum(9);
3362 ui->sliderBitrate->setMinimum(0);
3363 ui->sliderBitrate->setMaximum(13);
3367 case SettingsModel::VorbisEncoder:
3368 switch(m_settings->compressionRCMode())
3370 case SettingsModel::VBRMode:
3371 ui->sliderBitrate->setMinimum(-2);
3372 ui->sliderBitrate->setMaximum(10);
3375 ui->sliderBitrate->setMinimum(4);
3376 ui->sliderBitrate->setMaximum(63);
3380 case SettingsModel::AC3Encoder:
3381 switch(m_settings->compressionRCMode())
3383 case SettingsModel::VBRMode:
3384 ui->sliderBitrate->setMinimum(0);
3385 ui->sliderBitrate->setMaximum(16);
3388 ui->sliderBitrate->setMinimum(0);
3389 ui->sliderBitrate->setMaximum(18);
3393 case SettingsModel::AACEncoder:
3394 switch(m_settings->compressionRCMode())
3396 case SettingsModel::VBRMode:
3397 if(m_qaacEncoderAvailable)
3399 ui->sliderBitrate->setMinimum(0);
3400 ui->sliderBitrate->setMaximum(32);
3402 else if(m_fhgEncoderAvailable)
3404 ui->sliderBitrate->setMinimum(1);
3405 ui->sliderBitrate->setMaximum(6);
3409 ui->sliderBitrate->setMinimum(0);
3410 ui->sliderBitrate->setMaximum(20);
3414 ui->sliderBitrate->setMinimum(4);
3415 ui->sliderBitrate->setMaximum(63);
3419 case SettingsModel::FLACEncoder:
3420 ui->sliderBitrate->setMinimum(0);
3421 ui->sliderBitrate->setMaximum(8);
3423 case SettingsModel::OpusEncoder:
3424 ui->sliderBitrate->setMinimum(1);
3425 ui->sliderBitrate->setMaximum(32);
3427 case SettingsModel::DCAEncoder:
3428 ui->sliderBitrate->setMinimum(1);
3429 ui->sliderBitrate->setMaximum(128);
3431 case SettingsModel::PCMEncoder:
3432 ui->sliderBitrate->setMinimum(0);
3433 ui->sliderBitrate->setMaximum(2);
3434 ui->sliderBitrate->setValue(1);
3437 ui->sliderBitrate->setMinimum(0);
3438 ui->sliderBitrate->setMaximum(0);
3442 updateBitrate(ui->sliderBitrate->value());
3448 void MainWindow::updateBitrate(int value)
3450 m_settings->compressionBitrate(value);
3452 switch(m_settings->compressionRCMode())
3454 case SettingsModel::VBRMode:
3455 switch(m_settings->compressionEncoder())
3457 case SettingsModel::MP3Encoder:
3458 ui->labelBitrate->setText(tr("Quality Level %1").arg(9 - value));
3460 case SettingsModel::VorbisEncoder:
3461 ui->labelBitrate->setText(tr("Quality Level %1").arg(value));
3463 case SettingsModel::AACEncoder:
3464 if(m_qaacEncoderAvailable)
3466 ui->labelBitrate->setText(tr("Quality Level %1").arg(QString::number(qBound(0, value * 4 , 127))));
3468 else if(m_fhgEncoderAvailable)
3470 ui->labelBitrate->setText(tr("Quality Level %1").arg(QString::number(value)));
3474 ui->labelBitrate->setText(tr("Quality Level %1").arg(QString().sprintf("%.2f", static_cast<double>(value) / 20.0)));
3477 case SettingsModel::FLACEncoder:
3478 ui->labelBitrate->setText(tr("Compression %1").arg(value));
3480 case SettingsModel::OpusEncoder:
3481 ui->labelBitrate->setText(QString("≈ %1 kbps").arg(qMin(500, value * 8)));
3483 case SettingsModel::AC3Encoder:
3484 ui->labelBitrate->setText(tr("Quality Level %1").arg(qMin(1024, qMax(0, value * 64))));
3486 case SettingsModel::PCMEncoder:
3487 ui->labelBitrate->setText(tr("Uncompressed"));
3490 ui->labelBitrate->setText(QString::number(value));
3494 case SettingsModel::ABRMode:
3495 switch(m_settings->compressionEncoder())
3497 case SettingsModel::MP3Encoder:
3498 ui->labelBitrate->setText(QString("≈ %1 kbps").arg(SettingsModel::mp3Bitrates[value]));
3500 case SettingsModel::FLACEncoder:
3501 ui->labelBitrate->setText(tr("Compression %1").arg(value));
3503 case SettingsModel::AC3Encoder:
3504 ui->labelBitrate->setText(QString("≈ %1 kbps").arg(SettingsModel::ac3Bitrates[value]));
3506 case SettingsModel::PCMEncoder:
3507 ui->labelBitrate->setText(tr("Uncompressed"));
3510 ui->labelBitrate->setText(QString("≈ %1 kbps").arg(qMin(500, value * 8)));
3515 switch(m_settings->compressionEncoder())
3517 case SettingsModel::MP3Encoder:
3518 ui->labelBitrate->setText(QString("%1 kbps").arg(SettingsModel::mp3Bitrates[value]));
3520 case SettingsModel::FLACEncoder:
3521 ui->labelBitrate->setText(tr("Compression %1").arg(value));
3523 case SettingsModel::AC3Encoder:
3524 ui->labelBitrate->setText(QString("%1 kbps").arg(SettingsModel::ac3Bitrates[value]));
3526 case SettingsModel::DCAEncoder:
3527 ui->labelBitrate->setText(QString("%1 kbps").arg(value * 32));
3529 case SettingsModel::PCMEncoder:
3530 ui->labelBitrate->setText(tr("Uncompressed"));
3533 ui->labelBitrate->setText(QString("%1 kbps").arg(qMin(500, value * 8)));
3541 * Event for compression tab occurred
3543 void MainWindow::compressionTabEventOccurred(QWidget *sender, QEvent *event)
3545 static const QUrl helpUrl("http://lamexp.sourceforge.net/doc/FAQ.html#054010d9");
3547 if((sender == ui->labelCompressionHelp) && (event->type() == QEvent::MouseButtonPress))
3549 QDesktopServices::openUrl(helpUrl);
3553 // =========================================================
3554 // Advanced option slots
3555 // =========================================================
3558 * Lame algorithm quality changed
3560 void MainWindow::updateLameAlgoQuality(int value)
3567 text = tr("Best Quality (Slow)");
3570 text = tr("High Quality (Recommended)");
3573 text = tr("Acceptable Quality (Fast)");
3576 text = tr("Poor Quality (Very Fast)");
3582 m_settings->lameAlgoQuality(value);
3583 ui->labelLameAlgoQuality->setText(text);
3586 bool warning = (value == 0), notice = (value == 3);
3587 ui->labelLameAlgoQualityWarning->setVisible(warning);
3588 ui->labelLameAlgoQualityWarningIcon->setVisible(warning);
3589 ui->labelLameAlgoQualityNotice->setVisible(notice);
3590 ui->labelLameAlgoQualityNoticeIcon->setVisible(notice);
3591 ui->labelLameAlgoQualitySpacer->setVisible(warning || notice);
3595 * Bitrate management endabled/disabled
3597 void MainWindow::bitrateManagementEnabledChanged(bool checked)
3599 m_settings->bitrateManagementEnabled(checked);
3603 * Minimum bitrate has changed
3605 void MainWindow::bitrateManagementMinChanged(int value)
3607 if(value > ui->spinBoxBitrateManagementMax->value())
3609 ui->spinBoxBitrateManagementMin->setValue(ui->spinBoxBitrateManagementMax->value());
3610 m_settings->bitrateManagementMinRate(ui->spinBoxBitrateManagementMax->value());
3614 m_settings->bitrateManagementMinRate(value);
3619 * Maximum bitrate has changed
3621 void MainWindow::bitrateManagementMaxChanged(int value)
3623 if(value < ui->spinBoxBitrateManagementMin->value())
3625 ui->spinBoxBitrateManagementMax->setValue(ui->spinBoxBitrateManagementMin->value());
3626 m_settings->bitrateManagementMaxRate(ui->spinBoxBitrateManagementMin->value());
3630 m_settings->bitrateManagementMaxRate(value);
3635 * Channel mode has changed
3637 void MainWindow::channelModeChanged(int value)
3639 if(value >= 0) m_settings->lameChannelMode(value);
3643 * Sampling rate has changed
3645 void MainWindow::samplingRateChanged(int value)
3647 if(value >= 0) m_settings->samplingRate(value);
3651 * Nero AAC 2-Pass mode changed
3653 void MainWindow::neroAAC2PassChanged(bool checked)
3655 m_settings->neroAACEnable2Pass(checked);
3659 * Nero AAC profile mode changed
3661 void MainWindow::neroAACProfileChanged(int value)
3663 if(value >= 0) m_settings->aacEncProfile(value);
3667 * Aften audio coding mode changed
3669 void MainWindow::aftenCodingModeChanged(int value)
3671 if(value >= 0) m_settings->aftenAudioCodingMode(value);
3675 * Aften DRC mode changed
3677 void MainWindow::aftenDRCModeChanged(int value)
3679 if(value >= 0) m_settings->aftenDynamicRangeCompression(value);
3683 * Aften exponent search size changed
3685 void MainWindow::aftenSearchSizeChanged(int value)
3687 if(value >= 0) m_settings->aftenExponentSearchSize(value);
3691 * Aften fast bit allocation changed
3693 void MainWindow::aftenFastAllocationChanged(bool checked)
3695 m_settings->aftenFastBitAllocation(checked);
3700 * Opus encoder settings changed
3702 void MainWindow::opusSettingsChanged(void)
3704 m_settings->opusFramesize(ui->comboBoxOpusFramesize->currentIndex());
3705 m_settings->opusComplexity(ui->spinBoxOpusComplexity->value());
3706 m_settings->opusDisableResample(ui->checkBoxOpusDisableResample->isChecked());
3710 * Normalization filter enabled changed
3712 void MainWindow::normalizationEnabledChanged(bool checked)
3714 m_settings->normalizationFilterEnabled(checked);
3718 * Normalization max. volume changed
3720 void MainWindow::normalizationMaxVolumeChanged(double value)
3722 m_settings->normalizationFilterMaxVolume(static_cast<int>(value * 100.0));
3726 * Normalization equalization mode changed
3728 void MainWindow::normalizationModeChanged(int mode)
3730 m_settings->normalizationFilterEqualizationMode(mode);
3734 * Tone adjustment has changed (Bass)
3736 void MainWindow::toneAdjustBassChanged(double value)
3738 m_settings->toneAdjustBass(static_cast<int>(value * 100.0));
3739 ui->spinBoxToneAdjustBass->setPrefix((value > 0) ? "+" : QString());
3743 * Tone adjustment has changed (Treble)
3745 void MainWindow::toneAdjustTrebleChanged(double value)
3747 m_settings->toneAdjustTreble(static_cast<int>(value * 100.0));
3748 ui->spinBoxToneAdjustTreble->setPrefix((value > 0) ? "+" : QString());
3752 * Tone adjustment has been reset
3754 void MainWindow::toneAdjustTrebleReset(void)
3756 ui->spinBoxToneAdjustBass->setValue(m_settings->toneAdjustBassDefault());
3757 ui->spinBoxToneAdjustTreble->setValue(m_settings->toneAdjustTrebleDefault());
3758 toneAdjustBassChanged(ui->spinBoxToneAdjustBass->value());
3759 toneAdjustTrebleChanged(ui->spinBoxToneAdjustTreble->value());
3763 * Custom encoder parameters changed
3765 void MainWindow::customParamsChanged(void)
3767 ui->lineEditCustomParamLAME->setText(ui->lineEditCustomParamLAME->text().simplified());
3768 ui->lineEditCustomParamOggEnc->setText(ui->lineEditCustomParamOggEnc->text().simplified());
3769 ui->lineEditCustomParamNeroAAC->setText(ui->lineEditCustomParamNeroAAC->text().simplified());
3770 ui->lineEditCustomParamFLAC->setText(ui->lineEditCustomParamFLAC->text().simplified());
3771 ui->lineEditCustomParamAften->setText(ui->lineEditCustomParamAften->text().simplified());
3772 ui->lineEditCustomParamOpus->setText(ui->lineEditCustomParamOpus->text().simplified());
3774 bool customParamsUsed = false;
3775 if(!ui->lineEditCustomParamLAME->text().isEmpty()) customParamsUsed = true;
3776 if(!ui->lineEditCustomParamOggEnc->text().isEmpty()) customParamsUsed = true;
3777 if(!ui->lineEditCustomParamNeroAAC->text().isEmpty()) customParamsUsed = true;
3778 if(!ui->lineEditCustomParamFLAC->text().isEmpty()) customParamsUsed = true;
3779 if(!ui->lineEditCustomParamAften->text().isEmpty()) customParamsUsed = true;
3780 if(!ui->lineEditCustomParamOpus->text().isEmpty()) customParamsUsed = true;
3782 ui->labelCustomParamsIcon->setVisible(customParamsUsed);
3783 ui->labelCustomParamsText->setVisible(customParamsUsed);
3784 ui->labelCustomParamsSpacer->setVisible(customParamsUsed);
3786 m_settings->customParametersLAME(ui->lineEditCustomParamLAME->text());
3787 m_settings->customParametersOggEnc(ui->lineEditCustomParamOggEnc->text());
3788 m_settings->customParametersAacEnc(ui->lineEditCustomParamNeroAAC->text());
3789 m_settings->customParametersFLAC(ui->lineEditCustomParamFLAC->text());
3790 m_settings->customParametersAften(ui->lineEditCustomParamAften->text());
3791 m_settings->customParametersOpus(ui->lineEditCustomParamOpus->text());
3795 * Rename output files enabled changed
3797 void MainWindow::renameOutputEnabledChanged(bool checked)
3799 m_settings->renameOutputFilesEnabled(checked);
3803 * Rename output files patterm changed
3805 void MainWindow::renameOutputPatternChanged(void)
3807 QString temp = ui->lineEditRenamePattern->text().simplified();
3808 ui->lineEditRenamePattern->setText(temp.isEmpty() ? m_settings->renameOutputFilesPatternDefault() : temp);
3809 m_settings->renameOutputFilesPattern(ui->lineEditRenamePattern->text());
3813 * Rename output files patterm changed
3815 void MainWindow::renameOutputPatternChanged(const QString &text, bool silent)
3817 QString pattern(text.simplified());
3819 pattern.replace("<BaseName>", "The_White_Stripes_-_Fell_In_Love_With_A_Girl", Qt::CaseInsensitive);
3820 pattern.replace("<TrackNo>", "04", Qt::CaseInsensitive);
3821 pattern.replace("<Title>", "Fell In Love With A Girl", Qt::CaseInsensitive);
3822 pattern.replace("<Artist>", "The White Stripes", Qt::CaseInsensitive);
3823 pattern.replace("<Album>", "White Blood Cells", Qt::CaseInsensitive);
3824 pattern.replace("<Year>", "2001", Qt::CaseInsensitive);
3825 pattern.replace("<Comment>", "Encoded by LameXP", Qt::CaseInsensitive);
3827 const QString patternClean = lamexp_clean_filename(pattern);
3829 if(pattern.compare(patternClean))
3831 if(ui->lineEditRenamePattern->palette().color(QPalette::Text) != Qt::red)
3833 if(!silent) MessageBeep(MB_ICONERROR);
3834 SET_TEXT_COLOR(ui->lineEditRenamePattern, Qt::red);
3839 if(ui->lineEditRenamePattern->palette() != QPalette())
3841 if(!silent) MessageBeep(MB_ICONINFORMATION);
3842 ui->lineEditRenamePattern->setPalette(QPalette());
3846 ui->labelRanameExample->setText(patternClean);
3850 * Show list of rename macros
3852 void MainWindow::showRenameMacros(const QString &text)
3854 if(text.compare("reset", Qt::CaseInsensitive) == 0)
3856 ui->lineEditRenamePattern->setText(m_settings->renameOutputFilesPatternDefault());
3860 const QString format = QString("<tr><td><tt><%1></tt></td><td> </td><td>%2</td></tr>");
3862 QString message = QString("<table>");
3863 message += QString(format).arg("BaseName", tr("File name without extension"));
3864 message += QString(format).arg("TrackNo", tr("Track number with leading zero"));
3865 message += QString(format).arg("Title", tr("Track title"));
3866 message += QString(format).arg("Artist", tr("Artist name"));
3867 message += QString(format).arg("Album", tr("Album name"));
3868 message += QString(format).arg("Year", tr("Year with (at least) four digits"));
3869 message += QString(format).arg("Comment", tr("Comment"));
3870 message += "</table><br><br>";
3871 message += QString("%1<br>").arg(tr("Characters forbidden in file names:"));
3872 message += "<b><tt>\\ / : * ? < > |<br>";
3874 QMessageBox::information(this, tr("Rename Macros"), message, tr("Discard"));
3877 void MainWindow::forceStereoDownmixEnabledChanged(bool checked)
3879 m_settings->forceStereoDownmix(checked);
3883 * Maximum number of instances changed
3885 void MainWindow::updateMaximumInstances(int value)
3887 ui->labelMaxInstances->setText(tr("%n Instance(s)", "", value));
3888 m_settings->maximumInstances(ui->checkBoxAutoDetectInstances->isChecked() ? NULL : value);
3892 * Auto-detect number of instances
3894 void MainWindow::autoDetectInstancesChanged(bool checked)
3896 m_settings->maximumInstances(checked ? NULL : ui->sliderMaxInstances->value());
3900 * Browse for custom TEMP folder button clicked
3902 void MainWindow::browseCustomTempFolderButtonClicked(void)
3904 QString newTempFolder;
3906 if(lamexp_themes_enabled())
3908 newTempFolder = QFileDialog::getExistingDirectory(this, QString(), m_settings->customTempPath());
3912 QFileDialog dialog(this);
3913 dialog.setFileMode(QFileDialog::DirectoryOnly);
3914 dialog.setDirectory(m_settings->customTempPath());
3917 newTempFolder = dialog.selectedFiles().first();
3921 if(!newTempFolder.isEmpty())
3923 QFile writeTest(QString("%1/~%2.tmp").arg(newTempFolder, lamexp_rand_str()));
3924 if(writeTest.open(QIODevice::ReadWrite))
3927 ui->lineEditCustomTempFolder->setText(QDir::toNativeSeparators(newTempFolder));
3931 QMessageBox::warning(this, tr("Access Denied"), tr("Cannot write to the selected directory. Please choose another directory!"));
3937 * Custom TEMP folder changed
3939 void MainWindow::customTempFolderChanged(const QString &text)
3941 m_settings->customTempPath(QDir::fromNativeSeparators(text));
3945 * Use custom TEMP folder option changed
3947 void MainWindow::useCustomTempFolderChanged(bool checked)
3949 m_settings->customTempPathEnabled(!checked);
3953 * Help for custom parameters was requested
3955 void MainWindow::customParamsHelpRequested(QWidget *obj, QEvent *event)
3957 if(event->type() != QEvent::MouseButtonRelease)
3962 if(QMouseEvent *mouseEvent = dynamic_cast<QMouseEvent*>(event))
3964 QPoint pos = mouseEvent->pos();
3965 if(!(pos.x() <= obj->width() && pos.y() <= obj->height() && pos.x() >= 0 && pos.y() >= 0 && mouseEvent->button() != Qt::MidButton))
3971 if(obj == ui->helpCustomParamLAME) showCustomParamsHelpScreen("lame.exe", "--longhelp");
3972 else if(obj == ui->helpCustomParamOggEnc) showCustomParamsHelpScreen("oggenc2.exe", "--help");
3973 else if(obj == ui->helpCustomParamNeroAAC)
3975 if(m_qaacEncoderAvailable) showCustomParamsHelpScreen("qaac.exe", "--help");
3976 else if(m_fhgEncoderAvailable) showCustomParamsHelpScreen("fhgaacenc.exe", "");
3977 else if(m_neroEncoderAvailable) showCustomParamsHelpScreen("neroAacEnc.exe", "-help");
3978 else MessageBeep(MB_ICONERROR);
3980 else if(obj == ui->helpCustomParamFLAC) showCustomParamsHelpScreen("flac.exe", "--help");
3981 else if(obj == ui->helpCustomParamAften) showCustomParamsHelpScreen("aften.exe", "-h");
3982 else if(obj == ui->helpCustomParamOpus) showCustomParamsHelpScreen("opusenc.exe", "--help");
3983 else MessageBeep(MB_ICONERROR);
3987 * Show help for custom parameters
3989 void MainWindow::showCustomParamsHelpScreen(const QString &toolName, const QString &command)
3991 const QString binary = lamexp_lookup_tool(toolName);
3992 if(binary.isEmpty())
3994 MessageBeep(MB_ICONERROR);
3995 qWarning("customParamsHelpRequested: Binary could not be found!");
3999 QProcess *process = new QProcess();
4000 process->setProcessChannelMode(QProcess::MergedChannels);
4001 process->setReadChannel(QProcess::StandardOutput);
4002 process->start(binary, command.isEmpty() ? QStringList() : QStringList() << command);
4003 qApp->setOverrideCursor(QCursor(Qt::WaitCursor));
4005 if(process->waitForStarted(15000))
4007 qApp->processEvents();
4008 process->waitForFinished(15000);
4011 if(process->state() != QProcess::NotRunning)
4014 process->waitForFinished(-1);
4017 qApp->restoreOverrideCursor();
4018 QStringList output; bool spaceFlag = true;
4020 while(process->canReadLine())
4022 QString temp = QString::fromUtf8(process->readLine());
4023 TRIM_STRING_RIGHT(temp);
4026 if(!spaceFlag) { output << temp; spaceFlag = true; }
4030 output << temp; spaceFlag = false;
4034 LAMEXP_DELETE(process);
4036 if(output.count() < 1)
4038 qWarning("Empty output, cannot show help screen!");
4039 MessageBeep(MB_ICONERROR);
4042 LogViewDialog *dialog = new LogViewDialog(this);
4043 TEMP_HIDE_DROPBOX( dialog->exec(output); );
4044 LAMEXP_DELETE(dialog);
4047 void MainWindow::overwriteModeChanged(int id)
4049 if((id == SettingsModel::Overwrite_Replaces) && (m_settings->overwriteMode() != SettingsModel::Overwrite_Replaces))
4051 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)
4053 ui->radioButtonOverwriteModeKeepBoth->setChecked(m_settings->overwriteMode() == SettingsModel::Overwrite_KeepBoth);
4054 ui->radioButtonOverwriteModeSkipFile->setChecked(m_settings->overwriteMode() == SettingsModel::Overwrite_SkipFile);
4059 m_settings->overwriteMode(id);
4063 * Reset all advanced options to their defaults
4065 void MainWindow::resetAdvancedOptionsButtonClicked(void)
4067 ui->sliderLameAlgoQuality->setValue(m_settings->lameAlgoQualityDefault());
4068 ui->spinBoxBitrateManagementMin->setValue(m_settings->bitrateManagementMinRateDefault());
4069 ui->spinBoxBitrateManagementMax->setValue(m_settings->bitrateManagementMaxRateDefault());
4070 ui->spinBoxNormalizationFilter->setValue(static_cast<double>(m_settings->normalizationFilterMaxVolumeDefault()) / 100.0);
4071 ui->spinBoxToneAdjustBass->setValue(static_cast<double>(m_settings->toneAdjustBassDefault()) / 100.0);
4072 ui->spinBoxToneAdjustTreble->setValue(static_cast<double>(m_settings->toneAdjustTrebleDefault()) / 100.0);
4073 ui->spinBoxAftenSearchSize->setValue(m_settings->aftenExponentSearchSizeDefault());
4074 ui->spinBoxOpusComplexity->setValue(m_settings->opusComplexityDefault());
4075 ui->comboBoxMP3ChannelMode->setCurrentIndex(m_settings->lameChannelModeDefault());
4076 ui->comboBoxSamplingRate->setCurrentIndex(m_settings->samplingRateDefault());
4077 ui->comboBoxAACProfile->setCurrentIndex(m_settings->aacEncProfileDefault());
4078 ui->comboBoxAftenCodingMode->setCurrentIndex(m_settings->aftenAudioCodingModeDefault());
4079 ui->comboBoxAftenDRCMode->setCurrentIndex(m_settings->aftenDynamicRangeCompressionDefault());
4080 ui->comboBoxNormalizationMode->setCurrentIndex(m_settings->normalizationFilterEqualizationModeDefault());
4081 ui->comboBoxOpusFramesize->setCurrentIndex(m_settings->opusFramesizeDefault());
4082 SET_CHECKBOX_STATE(ui->checkBoxBitrateManagement, m_settings->bitrateManagementEnabledDefault());
4083 SET_CHECKBOX_STATE(ui->checkBoxNeroAAC2PassMode, m_settings->neroAACEnable2PassDefault());
4084 SET_CHECKBOX_STATE(ui->checkBoxNormalizationFilter, m_settings->normalizationFilterEnabledDefault());
4085 SET_CHECKBOX_STATE(ui->checkBoxAutoDetectInstances, (m_settings->maximumInstancesDefault() < 1));
4086 SET_CHECKBOX_STATE(ui->checkBoxUseSystemTempFolder, !m_settings->customTempPathEnabledDefault());
4087 SET_CHECKBOX_STATE(ui->checkBoxAftenFastAllocation, m_settings->aftenFastBitAllocationDefault());
4088 SET_CHECKBOX_STATE(ui->checkBoxRenameOutput, m_settings->renameOutputFilesEnabledDefault());
4089 SET_CHECKBOX_STATE(ui->checkBoxForceStereoDownmix, m_settings->forceStereoDownmixDefault());
4090 SET_CHECKBOX_STATE(ui->checkBoxOpusDisableResample, m_settings->opusDisableResampleDefault());
4091 ui->lineEditCustomParamLAME->setText(m_settings->customParametersLAMEDefault());
4092 ui->lineEditCustomParamOggEnc->setText(m_settings->customParametersOggEncDefault());
4093 ui->lineEditCustomParamNeroAAC->setText(m_settings->customParametersAacEncDefault());
4094 ui->lineEditCustomParamFLAC->setText(m_settings->customParametersFLACDefault());
4095 ui->lineEditCustomParamOpus->setText(m_settings->customParametersFLACDefault());
4096 ui->lineEditCustomTempFolder->setText(QDir::toNativeSeparators(m_settings->customTempPathDefault()));
4097 ui->lineEditRenamePattern->setText(m_settings->renameOutputFilesPatternDefault());
4098 if(m_settings->overwriteModeDefault() == SettingsModel::Overwrite_KeepBoth) ui->radioButtonOverwriteModeKeepBoth->click();
4099 if(m_settings->overwriteModeDefault() == SettingsModel::Overwrite_SkipFile) ui->radioButtonOverwriteModeSkipFile->click();
4100 if(m_settings->overwriteModeDefault() == SettingsModel::Overwrite_Replaces) ui->radioButtonOverwriteModeReplaces->click();
4101 customParamsChanged();
4102 ui->scrollArea->verticalScrollBar()->setValue(0);
4105 // =========================================================
4106 // Multi-instance handling slots
4107 // =========================================================
4110 * Other instance detected
4112 void MainWindow::notifyOtherInstance(void)
4114 if(!m_banner->isVisible())
4116 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);
4122 * Add file from another instance
4124 void MainWindow::addFileDelayed(const QString &filePath, bool tryASAP)
4126 if(tryASAP && !m_delayedFileTimer->isActive())
4128 qDebug("Received file: %s", filePath.toUtf8().constData());
4129 m_delayedFileList->append(filePath);
4130 QTimer::singleShot(0, this, SLOT(handleDelayedFiles()));
4133 m_delayedFileTimer->stop();
4134 qDebug("Received file: %s", filePath.toUtf8().constData());
4135 m_delayedFileList->append(filePath);
4136 m_delayedFileTimer->start(5000);
4140 * Add files from another instance
4142 void MainWindow::addFilesDelayed(const QStringList &filePaths, bool tryASAP)
4144 if(tryASAP && !m_delayedFileTimer->isActive())
4146 qDebug("Received %d file(s).", filePaths.count());
4147 m_delayedFileList->append(filePaths);
4148 QTimer::singleShot(0, this, SLOT(handleDelayedFiles()));
4152 m_delayedFileTimer->stop();
4153 qDebug("Received %d file(s).", filePaths.count());
4154 m_delayedFileList->append(filePaths);
4155 m_delayedFileTimer->start(5000);
4160 * Add folder from another instance
4162 void MainWindow::addFolderDelayed(const QString &folderPath, bool recursive)
4164 if(!m_banner->isVisible())
4166 addFolder(folderPath, recursive, true);
4170 // =========================================================
4172 // =========================================================
4175 * Restore the override cursor
4177 void MainWindow::restoreCursor(void)
4179 QApplication::restoreOverrideCursor();