Changed the method to synchronize the analyzer threads: We now use QSet to maintain...
[LameXP.git] / src / Dialog_MainWindow.cpp
blob6050ce10760f80ec2dd63bb9e14e4cdd02e4d86f
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2012 LoRd_MuldeR <MuldeR2@GMX.de>
4 //
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; either version 2 of the License, or
8 // (at your option) any later version.
9 //
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"
24 //LameXP includes
25 #include "Global.h"
26 #include "Resource.h"
27 #include "Dialog_WorkingBanner.h"
28 #include "Dialog_MetaInfo.h"
29 #include "Dialog_About.h"
30 #include "Dialog_Update.h"
31 #include "Dialog_DropBox.h"
32 #include "Dialog_CueImport.h"
33 #include "Thread_FileAnalyzer.h"
34 #include "Thread_FileAnalyzer_ST.h"
35 #include "Thread_MessageHandler.h"
36 #include "Model_MetaInfo.h"
37 #include "Model_Settings.h"
38 #include "Model_FileList.h"
39 #include "Model_FileSystem.h"
40 #include "WinSevenTaskbar.h"
41 #include "Registry_Decoder.h"
42 #include "ShellIntegration.h"
44 //Qt includes
45 #include <QMessageBox>
46 #include <QTimer>
47 #include <QDesktopWidget>
48 #include <QDate>
49 #include <QFileDialog>
50 #include <QInputDialog>
51 #include <QFileSystemModel>
52 #include <QDesktopServices>
53 #include <QUrl>
54 #include <QPlastiqueStyle>
55 #include <QCleanlooksStyle>
56 #include <QWindowsVistaStyle>
57 #include <QWindowsStyle>
58 #include <QSysInfo>
59 #include <QDragEnterEvent>
60 #include <QMimeData>
61 #include <QProcess>
62 #include <QUuid>
63 #include <QProcessEnvironment>
64 #include <QCryptographicHash>
65 #include <QTranslator>
66 #include <QResource>
67 #include <QScrollBar>
69 //System includes
70 #include <MMSystem.h>
71 #include <ShellAPI.h>
73 //Helper macros
74 #define ABORT_IF_BUSY if(m_banner->isVisible() || m_delayedFileTimer->isActive()) { MessageBeep(MB_ICONEXCLAMATION); return; }
75 #define SET_TEXT_COLOR(WIDGET,COLOR) { QPalette _palette = WIDGET->palette(); _palette.setColor(QPalette::WindowText, (COLOR)); _palette.setColor(QPalette::Text, (COLOR)); WIDGET->setPalette(_palette); }
76 #define SET_FONT_BOLD(WIDGET,BOLD) { QFont _font = WIDGET->font(); _font.setBold(BOLD); WIDGET->setFont(_font); }
77 #define LINK(URL) QString("<a href=\"%1\">%2</a>").arg(URL).arg(QString(URL).replace("-", "&minus;"))
78 #define FSLINK(PATH) QString("<a href=\"file:///%1\">%2</a>").arg(PATH).arg(QString(PATH).replace("-", "&minus;"))
79 #define TEMP_HIDE_DROPBOX(CMD) { bool __dropBoxVisible = m_dropBox->isVisible(); if(__dropBoxVisible) m_dropBox->hide(); {CMD}; if(__dropBoxVisible) m_dropBox->show(); }
80 #define USE_NATIVE_FILE_DIALOG (lamexp_themes_enabled() || ((QSysInfo::windowsVersion() & QSysInfo::WV_NT_based) < QSysInfo::WV_XP))
81 #define CENTER_CURRENT_OUTPUT_FOLDER_DELAYED QTimer::singleShot(125, this, SLOT(centerOutputFolderModel()))
82 #define SET_MODEL(VIEW, MODEL) { QItemSelectionModel *_tmp = (VIEW)->selectionModel(); (VIEW)->setModel(MODEL); LAMEXP_DELETE(_tmp); }
84 ////////////////////////////////////////////////////////////
85 // Constructor
86 ////////////////////////////////////////////////////////////
88 MainWindow::MainWindow(FileListModel *fileListModel, AudioFileModel *metaInfo, SettingsModel *settingsModel, QWidget *parent)
90 QMainWindow(parent),
91 m_fileListModel(fileListModel),
92 m_metaData(metaInfo),
93 m_settings(settingsModel),
94 m_fileSystemModel(NULL),
95 m_neroEncoderAvailable(lamexp_check_tool("neroAacEnc.exe") && lamexp_check_tool("neroAacDec.exe") && lamexp_check_tool("neroAacTag.exe")),
96 m_fhgEncoderAvailable(lamexp_check_tool("fhgaacenc.exe") && lamexp_check_tool("enc_fhgaac.dll") && lamexp_check_tool("nsutil.dll") && lamexp_check_tool("libmp4v2.dll")),
97 m_qaacEncoderAvailable(lamexp_check_tool("qaac.exe") && lamexp_check_tool("libsoxrate.dll")),
98 m_accepted(false),
99 m_firstTimeShown(true),
100 m_outputFolderViewCentering(false),
101 m_outputFolderViewInitCounter(0)
103 //Init the dialog, from the .ui file
104 setupUi(this);
105 setWindowFlags(windowFlags() ^ Qt::WindowMaximizeButtonHint);
107 //Register meta types
108 qRegisterMetaType<AudioFileModel>("AudioFileModel");
110 //Enabled main buttons
111 connect(buttonAbout, SIGNAL(clicked()), this, SLOT(aboutButtonClicked()));
112 connect(buttonStart, SIGNAL(clicked()), this, SLOT(encodeButtonClicked()));
113 connect(buttonQuit, SIGNAL(clicked()), this, SLOT(closeButtonClicked()));
115 //Setup tab widget
116 tabWidget->setCurrentIndex(0);
117 connect(tabWidget, SIGNAL(currentChanged(int)), this, SLOT(tabPageChanged(int)));
119 //Setup "Source" tab
120 sourceFileView->setModel(m_fileListModel);
121 sourceFileView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
122 sourceFileView->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);
123 sourceFileView->setContextMenuPolicy(Qt::CustomContextMenu);
124 sourceFileView->viewport()->installEventFilter(this);
125 m_dropNoteLabel = new QLabel(sourceFileView);
126 m_dropNoteLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
127 SET_FONT_BOLD(m_dropNoteLabel, true);
128 SET_TEXT_COLOR(m_dropNoteLabel, Qt::darkGray);
129 m_sourceFilesContextMenu = new QMenu();
130 m_showDetailsContextAction = m_sourceFilesContextMenu->addAction(QIcon(":/icons/zoom.png"), "N/A");
131 m_previewContextAction = m_sourceFilesContextMenu->addAction(QIcon(":/icons/sound.png"), "N/A");
132 m_findFileContextAction = m_sourceFilesContextMenu->addAction(QIcon(":/icons/folder_go.png"), "N/A");
133 m_sourceFilesContextMenu->addSeparator();
134 m_exportCsvContextAction = m_sourceFilesContextMenu->addAction(QIcon(":/icons/table_save.png"), "N/A");
135 m_importCsvContextAction = m_sourceFilesContextMenu->addAction(QIcon(":/icons/folder_table.png"), "N/A");
136 SET_FONT_BOLD(m_showDetailsContextAction, true);
137 connect(buttonAddFiles, SIGNAL(clicked()), this, SLOT(addFilesButtonClicked()));
138 connect(buttonRemoveFile, SIGNAL(clicked()), this, SLOT(removeFileButtonClicked()));
139 connect(buttonClearFiles, SIGNAL(clicked()), this, SLOT(clearFilesButtonClicked()));
140 connect(buttonFileUp, SIGNAL(clicked()), this, SLOT(fileUpButtonClicked()));
141 connect(buttonFileDown, SIGNAL(clicked()), this, SLOT(fileDownButtonClicked()));
142 connect(buttonShowDetails, SIGNAL(clicked()), this, SLOT(showDetailsButtonClicked()));
143 connect(m_fileListModel, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(sourceModelChanged()));
144 connect(m_fileListModel, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(sourceModelChanged()));
145 connect(m_fileListModel, SIGNAL(modelReset()), this, SLOT(sourceModelChanged()));
146 connect(sourceFileView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(sourceFilesContextMenu(QPoint)));
147 connect(sourceFileView->verticalScrollBar(), SIGNAL(sliderMoved(int)), this, SLOT(sourceFilesScrollbarMoved(int)));
148 connect(sourceFileView->verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(sourceFilesScrollbarMoved(int)));
149 connect(m_showDetailsContextAction, SIGNAL(triggered(bool)), this, SLOT(showDetailsButtonClicked()));
150 connect(m_previewContextAction, SIGNAL(triggered(bool)), this, SLOT(previewContextActionTriggered()));
151 connect(m_findFileContextAction, SIGNAL(triggered(bool)), this, SLOT(findFileContextActionTriggered()));
152 connect(m_exportCsvContextAction, SIGNAL(triggered(bool)), this, SLOT(exportCsvContextActionTriggered()));
153 connect(m_importCsvContextAction, SIGNAL(triggered(bool)), this, SLOT(importCsvContextActionTriggered()));
155 //Setup "Output" tab
156 outputFolderView->setHeaderHidden(true);
157 outputFolderView->setAnimated(false);
158 outputFolderView->setMouseTracking(false);
159 outputFolderView->setContextMenuPolicy(Qt::CustomContextMenu);
160 outputFolderView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
161 outputFolderView->installEventFilter(this);
162 outputFoldersEditorLabel->installEventFilter(this);
163 outputFoldersFovoritesLabel->installEventFilter(this);
164 while(saveToSourceFolderCheckBox->isChecked() != m_settings->outputToSourceDir()) saveToSourceFolderCheckBox->click();
165 prependRelativePathCheckBox->setChecked(m_settings->prependRelativeSourcePath());
166 connect(outputFolderView, SIGNAL(clicked(QModelIndex)), this, SLOT(outputFolderViewClicked(QModelIndex)));
167 connect(outputFolderView, SIGNAL(activated(QModelIndex)), this, SLOT(outputFolderViewClicked(QModelIndex)));
168 connect(outputFolderView, SIGNAL(pressed(QModelIndex)), this, SLOT(outputFolderViewClicked(QModelIndex)));
169 connect(outputFolderView, SIGNAL(entered(QModelIndex)), this, SLOT(outputFolderViewMoved(QModelIndex)));
170 connect(outputFolderView, SIGNAL(expanded(QModelIndex)), this, SLOT(outputFolderItemExpanded(QModelIndex)));
171 connect(buttonMakeFolder, SIGNAL(clicked()), this, SLOT(makeFolderButtonClicked()));
172 connect(buttonGotoHome, SIGNAL(clicked()), SLOT(gotoHomeFolderButtonClicked()));
173 connect(buttonGotoDesktop, SIGNAL(clicked()), this, SLOT(gotoDesktopButtonClicked()));
174 connect(buttonGotoMusic, SIGNAL(clicked()), this, SLOT(gotoMusicFolderButtonClicked()));
175 connect(saveToSourceFolderCheckBox, SIGNAL(clicked()), this, SLOT(saveToSourceFolderChanged()));
176 connect(prependRelativePathCheckBox, SIGNAL(clicked()), this, SLOT(prependRelativePathChanged()));
177 connect(outputFolderEdit, SIGNAL(editingFinished()), this, SLOT(outputFolderEditFinished()));
178 if(m_outputFolderContextMenu = new QMenu())
180 m_showFolderContextAction = m_outputFolderContextMenu->addAction(QIcon(":/icons/zoom.png"), "N/A");
181 m_refreshFolderContextAction = m_outputFolderContextMenu->addAction(QIcon(":/icons/arrow_refresh.png"), "N/A");
182 m_outputFolderContextMenu->setDefaultAction(m_showFolderContextAction);
183 connect(outputFolderView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(outputFolderContextMenu(QPoint)));
184 connect(m_showFolderContextAction, SIGNAL(triggered(bool)), this, SLOT(showFolderContextActionTriggered()));
185 connect(m_refreshFolderContextAction, SIGNAL(triggered(bool)), this, SLOT(refreshFolderContextActionTriggered()));
187 if(m_outputFolderFavoritesMenu = new QMenu())
189 m_addFavoriteFolderAction = m_outputFolderFavoritesMenu->addAction(QIcon(":/icons/add.png"), "N/A");
190 m_outputFolderFavoritesMenu->insertSeparator(m_addFavoriteFolderAction);
191 connect(m_addFavoriteFolderAction, SIGNAL(triggered(bool)), this, SLOT(addFavoriteFolderActionTriggered()));
193 outputFolderEdit->setVisible(false);
194 outputFolderLabel->installEventFilter(this);
195 if(m_outputFolderNoteBox = new QLabel(outputFolderView))
197 m_outputFolderNoteBox->setAutoFillBackground(true);
198 m_outputFolderNoteBox->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
199 m_outputFolderNoteBox->setFrameShape(QFrame::StyledPanel);
200 SET_FONT_BOLD(m_outputFolderNoteBox, true);
201 m_outputFolderNoteBox->hide();
204 outputFolderViewClicked(QModelIndex());
205 refreshFavorites();
207 //Setup "Meta Data" tab
208 m_metaInfoModel = new MetaInfoModel(m_metaData, 6);
209 m_metaInfoModel->clearData();
210 m_metaInfoModel->setData(m_metaInfoModel->index(4, 1), m_settings->metaInfoPosition());
211 metaDataView->setModel(m_metaInfoModel);
212 metaDataView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
213 metaDataView->verticalHeader()->hide();
214 metaDataView->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);
215 while(writeMetaDataCheckBox->isChecked() != m_settings->writeMetaTags()) writeMetaDataCheckBox->click();
216 generatePlaylistCheckBox->setChecked(m_settings->createPlaylist());
217 connect(buttonEditMeta, SIGNAL(clicked()), this, SLOT(editMetaButtonClicked()));
218 connect(buttonClearMeta, SIGNAL(clicked()), this, SLOT(clearMetaButtonClicked()));
219 connect(writeMetaDataCheckBox, SIGNAL(clicked()), this, SLOT(metaTagsEnabledChanged()));
220 connect(generatePlaylistCheckBox, SIGNAL(clicked()), this, SLOT(playlistEnabledChanged()));
222 //Setup "Compression" tab
223 m_encoderButtonGroup = new QButtonGroup(this);
224 m_encoderButtonGroup->addButton(radioButtonEncoderMP3, SettingsModel::MP3Encoder);
225 m_encoderButtonGroup->addButton(radioButtonEncoderVorbis, SettingsModel::VorbisEncoder);
226 m_encoderButtonGroup->addButton(radioButtonEncoderAAC, SettingsModel::AACEncoder);
227 m_encoderButtonGroup->addButton(radioButtonEncoderAC3, SettingsModel::AC3Encoder);
228 m_encoderButtonGroup->addButton(radioButtonEncoderFLAC, SettingsModel::FLACEncoder);
229 m_encoderButtonGroup->addButton(radioButtonEncoderDCA, SettingsModel::DCAEncoder);
230 m_encoderButtonGroup->addButton(radioButtonEncoderPCM, SettingsModel::PCMEncoder);
231 m_modeButtonGroup = new QButtonGroup(this);
232 m_modeButtonGroup->addButton(radioButtonModeQuality, SettingsModel::VBRMode);
233 m_modeButtonGroup->addButton(radioButtonModeAverageBitrate, SettingsModel::ABRMode);
234 m_modeButtonGroup->addButton(radioButtonConstBitrate, SettingsModel::CBRMode);
235 radioButtonEncoderAAC->setEnabled(m_neroEncoderAvailable || m_fhgEncoderAvailable || m_qaacEncoderAvailable);
236 radioButtonEncoderMP3->setChecked(m_settings->compressionEncoder() == SettingsModel::MP3Encoder);
237 radioButtonEncoderVorbis->setChecked(m_settings->compressionEncoder() == SettingsModel::VorbisEncoder);
238 radioButtonEncoderAAC->setChecked((m_settings->compressionEncoder() == SettingsModel::AACEncoder) && (m_neroEncoderAvailable || m_fhgEncoderAvailable || m_qaacEncoderAvailable));
239 radioButtonEncoderAC3->setChecked(m_settings->compressionEncoder() == SettingsModel::AC3Encoder);
240 radioButtonEncoderFLAC->setChecked(m_settings->compressionEncoder() == SettingsModel::FLACEncoder);
241 radioButtonEncoderDCA->setChecked(m_settings->compressionEncoder() == SettingsModel::DCAEncoder);
242 radioButtonEncoderPCM->setChecked(m_settings->compressionEncoder() == SettingsModel::PCMEncoder);
243 radioButtonModeQuality->setChecked(m_settings->compressionRCMode() == SettingsModel::VBRMode);
244 radioButtonModeAverageBitrate->setChecked(m_settings->compressionRCMode() == SettingsModel::ABRMode);
245 radioButtonConstBitrate->setChecked(m_settings->compressionRCMode() == SettingsModel::CBRMode);
246 sliderBitrate->setValue(m_settings->compressionBitrate());
247 connect(m_encoderButtonGroup, SIGNAL(buttonClicked(int)), this, SLOT(updateEncoder(int)));
248 connect(m_modeButtonGroup, SIGNAL(buttonClicked(int)), this, SLOT(updateRCMode(int)));
249 connect(sliderBitrate, SIGNAL(valueChanged(int)), this, SLOT(updateBitrate(int)));
250 updateEncoder(m_encoderButtonGroup->checkedId());
252 //Setup "Advanced Options" tab
253 sliderLameAlgoQuality->setValue(m_settings->lameAlgoQuality());
254 if(m_settings->maximumInstances() > 0) sliderMaxInstances->setValue(m_settings->maximumInstances());
255 spinBoxBitrateManagementMin->setValue(m_settings->bitrateManagementMinRate());
256 spinBoxBitrateManagementMax->setValue(m_settings->bitrateManagementMaxRate());
257 spinBoxNormalizationFilter->setValue(static_cast<double>(m_settings->normalizationFilterMaxVolume()) / 100.0);
258 spinBoxToneAdjustBass->setValue(static_cast<double>(m_settings->toneAdjustBass()) / 100.0);
259 spinBoxToneAdjustTreble->setValue(static_cast<double>(m_settings->toneAdjustTreble()) / 100.0);
260 spinBoxAftenSearchSize->setValue(m_settings->aftenExponentSearchSize());
261 comboBoxMP3ChannelMode->setCurrentIndex(m_settings->lameChannelMode());
262 comboBoxSamplingRate->setCurrentIndex(m_settings->samplingRate());
263 comboBoxAACProfile->setCurrentIndex(m_settings->aacEncProfile());
264 comboBoxAftenCodingMode->setCurrentIndex(m_settings->aftenAudioCodingMode());
265 comboBoxAftenDRCMode->setCurrentIndex(m_settings->aftenDynamicRangeCompression());
266 comboBoxNormalizationMode->setCurrentIndex(m_settings->normalizationFilterEqualizationMode());
267 while(checkBoxBitrateManagement->isChecked() != m_settings->bitrateManagementEnabled()) checkBoxBitrateManagement->click();
268 while(checkBoxNeroAAC2PassMode->isChecked() != m_settings->neroAACEnable2Pass()) checkBoxNeroAAC2PassMode->click();
269 while(checkBoxAftenFastAllocation->isChecked() != m_settings->aftenFastBitAllocation()) checkBoxAftenFastAllocation->click();
270 while(checkBoxNormalizationFilter->isChecked() != m_settings->normalizationFilterEnabled()) checkBoxNormalizationFilter->click();
271 while(checkBoxAutoDetectInstances->isChecked() != (m_settings->maximumInstances() < 1)) checkBoxAutoDetectInstances->click();
272 while(checkBoxUseSystemTempFolder->isChecked() == m_settings->customTempPathEnabled()) checkBoxUseSystemTempFolder->click();
273 while(checkBoxRenameOutput->isChecked() != m_settings->renameOutputFilesEnabled()) checkBoxRenameOutput->click();
274 while(checkBoxForceStereoDownmix->isChecked() != m_settings->forceStereoDownmix()) checkBoxForceStereoDownmix->click();
275 checkBoxNeroAAC2PassMode->setEnabled(!(m_fhgEncoderAvailable || m_qaacEncoderAvailable));
276 lineEditCustomParamLAME->setText(m_settings->customParametersLAME());
277 lineEditCustomParamOggEnc->setText(m_settings->customParametersOggEnc());
278 lineEditCustomParamNeroAAC->setText(m_settings->customParametersAacEnc());
279 lineEditCustomParamFLAC->setText(m_settings->customParametersFLAC());
280 lineEditCustomParamAften->setText(m_settings->customParametersAften());
281 lineEditCustomTempFolder->setText(QDir::toNativeSeparators(m_settings->customTempPath()));
282 lineEditRenamePattern->setText(m_settings->renameOutputFilesPattern());
283 connect(sliderLameAlgoQuality, SIGNAL(valueChanged(int)), this, SLOT(updateLameAlgoQuality(int)));
284 connect(checkBoxBitrateManagement, SIGNAL(clicked(bool)), this, SLOT(bitrateManagementEnabledChanged(bool)));
285 connect(spinBoxBitrateManagementMin, SIGNAL(valueChanged(int)), this, SLOT(bitrateManagementMinChanged(int)));
286 connect(spinBoxBitrateManagementMax, SIGNAL(valueChanged(int)), this, SLOT(bitrateManagementMaxChanged(int)));
287 connect(comboBoxMP3ChannelMode, SIGNAL(currentIndexChanged(int)), this, SLOT(channelModeChanged(int)));
288 connect(comboBoxSamplingRate, SIGNAL(currentIndexChanged(int)), this, SLOT(samplingRateChanged(int)));
289 connect(checkBoxNeroAAC2PassMode, SIGNAL(clicked(bool)), this, SLOT(neroAAC2PassChanged(bool)));
290 connect(comboBoxAACProfile, SIGNAL(currentIndexChanged(int)), this, SLOT(neroAACProfileChanged(int)));
291 connect(checkBoxNormalizationFilter, SIGNAL(clicked(bool)), this, SLOT(normalizationEnabledChanged(bool)));
292 connect(comboBoxAftenCodingMode, SIGNAL(currentIndexChanged(int)), this, SLOT(aftenCodingModeChanged(int)));
293 connect(comboBoxAftenDRCMode, SIGNAL(currentIndexChanged(int)), this, SLOT(aftenDRCModeChanged(int)));
294 connect(spinBoxAftenSearchSize, SIGNAL(valueChanged(int)), this, SLOT(aftenSearchSizeChanged(int)));
295 connect(checkBoxAftenFastAllocation, SIGNAL(clicked(bool)), this, SLOT(aftenFastAllocationChanged(bool)));
296 connect(spinBoxNormalizationFilter, SIGNAL(valueChanged(double)), this, SLOT(normalizationMaxVolumeChanged(double)));
297 connect(comboBoxNormalizationMode, SIGNAL(currentIndexChanged(int)), this, SLOT(normalizationModeChanged(int)));
298 connect(spinBoxToneAdjustBass, SIGNAL(valueChanged(double)), this, SLOT(toneAdjustBassChanged(double)));
299 connect(spinBoxToneAdjustTreble, SIGNAL(valueChanged(double)), this, SLOT(toneAdjustTrebleChanged(double)));
300 connect(buttonToneAdjustReset, SIGNAL(clicked()), this, SLOT(toneAdjustTrebleReset()));
301 connect(lineEditCustomParamLAME, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
302 connect(lineEditCustomParamOggEnc, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
303 connect(lineEditCustomParamNeroAAC, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
304 connect(lineEditCustomParamFLAC, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
305 connect(lineEditCustomParamAften, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
306 connect(sliderMaxInstances, SIGNAL(valueChanged(int)), this, SLOT(updateMaximumInstances(int)));
307 connect(checkBoxAutoDetectInstances, SIGNAL(clicked(bool)), this, SLOT(autoDetectInstancesChanged(bool)));
308 connect(buttonBrowseCustomTempFolder, SIGNAL(clicked()), this, SLOT(browseCustomTempFolderButtonClicked()));
309 connect(lineEditCustomTempFolder, SIGNAL(textChanged(QString)), this, SLOT(customTempFolderChanged(QString)));
310 connect(checkBoxUseSystemTempFolder, SIGNAL(clicked(bool)), this, SLOT(useCustomTempFolderChanged(bool)));
311 connect(buttonResetAdvancedOptions, SIGNAL(clicked()), this, SLOT(resetAdvancedOptionsButtonClicked()));
312 connect(checkBoxRenameOutput, SIGNAL(clicked(bool)), this, SLOT(renameOutputEnabledChanged(bool)));
313 connect(lineEditRenamePattern, SIGNAL(editingFinished()), this, SLOT(renameOutputPatternChanged()));
314 connect(lineEditRenamePattern, SIGNAL(textChanged(QString)), this, SLOT(renameOutputPatternChanged(QString)));
315 connect(labelShowRenameMacros, SIGNAL(linkActivated(QString)), this, SLOT(showRenameMacros(QString)));
316 connect(checkBoxForceStereoDownmix, SIGNAL(clicked(bool)), this, SLOT(forceStereoDownmixEnabledChanged(bool)));
317 updateLameAlgoQuality(sliderLameAlgoQuality->value());
318 updateMaximumInstances(sliderMaxInstances->value());
319 toneAdjustTrebleChanged(spinBoxToneAdjustTreble->value());
320 toneAdjustBassChanged(spinBoxToneAdjustBass->value());
321 customParamsChanged();
323 //Activate file menu actions
324 actionOpenFolder->setData(QVariant::fromValue<bool>(false));
325 actionOpenFolderRecursively->setData(QVariant::fromValue<bool>(true));
326 connect(actionOpenFolder, SIGNAL(triggered()), this, SLOT(openFolderActionActivated()));
327 connect(actionOpenFolderRecursively, SIGNAL(triggered()), this, SLOT(openFolderActionActivated()));
329 //Activate view menu actions
330 m_tabActionGroup = new QActionGroup(this);
331 m_tabActionGroup->addAction(actionSourceFiles);
332 m_tabActionGroup->addAction(actionOutputDirectory);
333 m_tabActionGroup->addAction(actionCompression);
334 m_tabActionGroup->addAction(actionMetaData);
335 m_tabActionGroup->addAction(actionAdvancedOptions);
336 actionSourceFiles->setData(0);
337 actionOutputDirectory->setData(1);
338 actionMetaData->setData(2);
339 actionCompression->setData(3);
340 actionAdvancedOptions->setData(4);
341 actionSourceFiles->setChecked(true);
342 connect(m_tabActionGroup, SIGNAL(triggered(QAction*)), this, SLOT(tabActionActivated(QAction*)));
344 //Activate style menu actions
345 m_styleActionGroup = new QActionGroup(this);
346 m_styleActionGroup->addAction(actionStylePlastique);
347 m_styleActionGroup->addAction(actionStyleCleanlooks);
348 m_styleActionGroup->addAction(actionStyleWindowsVista);
349 m_styleActionGroup->addAction(actionStyleWindowsXP);
350 m_styleActionGroup->addAction(actionStyleWindowsClassic);
351 actionStylePlastique->setData(0);
352 actionStyleCleanlooks->setData(1);
353 actionStyleWindowsVista->setData(2);
354 actionStyleWindowsXP->setData(3);
355 actionStyleWindowsClassic->setData(4);
356 actionStylePlastique->setChecked(true);
357 actionStyleWindowsXP->setEnabled((QSysInfo::windowsVersion() & QSysInfo::WV_NT_based) >= QSysInfo::WV_XP && lamexp_themes_enabled());
358 actionStyleWindowsVista->setEnabled((QSysInfo::windowsVersion() & QSysInfo::WV_NT_based) >= QSysInfo::WV_VISTA && lamexp_themes_enabled());
359 connect(m_styleActionGroup, SIGNAL(triggered(QAction*)), this, SLOT(styleActionActivated(QAction*)));
360 styleActionActivated(NULL);
362 //Populate the language menu
363 m_languageActionGroup = new QActionGroup(this);
364 QStringList translations = lamexp_query_translations();
365 while(!translations.isEmpty())
367 QString langId = translations.takeFirst();
368 QAction *currentLanguage = new QAction(this);
369 currentLanguage->setData(langId);
370 currentLanguage->setText(lamexp_translation_name(langId));
371 currentLanguage->setIcon(QIcon(QString(":/flags/%1.png").arg(langId)));
372 currentLanguage->setCheckable(true);
373 m_languageActionGroup->addAction(currentLanguage);
374 menuLanguage->insertAction(actionLoadTranslationFromFile, currentLanguage);
376 menuLanguage->insertSeparator(actionLoadTranslationFromFile);
377 connect(actionLoadTranslationFromFile, SIGNAL(triggered(bool)), this, SLOT(languageFromFileActionActivated(bool)));
378 connect(m_languageActionGroup, SIGNAL(triggered(QAction*)), this, SLOT(languageActionActivated(QAction*)));
380 //Activate tools menu actions
381 actionDisableUpdateReminder->setChecked(!m_settings->autoUpdateEnabled());
382 actionDisableSounds->setChecked(!m_settings->soundsEnabled());
383 actionDisableNeroAacNotifications->setChecked(!m_settings->neroAacNotificationsEnabled());
384 actionDisableSlowStartupNotifications->setChecked(!m_settings->antivirNotificationsEnabled());
385 actionDisableShellIntegration->setChecked(!m_settings->shellIntegrationEnabled());
386 actionDisableShellIntegration->setDisabled(lamexp_portable_mode() && actionDisableShellIntegration->isChecked());
387 actionCheckForBetaUpdates->setChecked(m_settings->autoUpdateCheckBeta() || lamexp_version_demo());
388 actionCheckForBetaUpdates->setEnabled(!lamexp_version_demo());
389 actionHibernateComputer->setChecked(m_settings->hibernateComputer());
390 actionHibernateComputer->setEnabled(lamexp_is_hibernation_supported());
391 connect(actionDisableUpdateReminder, SIGNAL(triggered(bool)), this, SLOT(disableUpdateReminderActionTriggered(bool)));
392 connect(actionDisableSounds, SIGNAL(triggered(bool)), this, SLOT(disableSoundsActionTriggered(bool)));
393 connect(actionDisableNeroAacNotifications, SIGNAL(triggered(bool)), this, SLOT(disableNeroAacNotificationsActionTriggered(bool)));
394 connect(actionDisableSlowStartupNotifications, SIGNAL(triggered(bool)), this, SLOT(disableSlowStartupNotificationsActionTriggered(bool)));
395 connect(actionDisableShellIntegration, SIGNAL(triggered(bool)), this, SLOT(disableShellIntegrationActionTriggered(bool)));
396 connect(actionShowDropBoxWidget, SIGNAL(triggered(bool)), this, SLOT(showDropBoxWidgetActionTriggered(bool)));
397 connect(actionHibernateComputer, SIGNAL(triggered(bool)), this, SLOT(hibernateComputerActionTriggered(bool)));
398 connect(actionCheckForBetaUpdates, SIGNAL(triggered(bool)), this, SLOT(checkForBetaUpdatesActionTriggered(bool)));
399 connect(actionImportCueSheet, SIGNAL(triggered(bool)), this, SLOT(importCueSheetActionTriggered(bool)));
401 //Activate help menu actions
402 actionVisitHomepage->setData(QString::fromLatin1(lamexp_website_url()));
403 actionVisitSupport->setData(QString::fromLatin1(lamexp_support_url()));
404 actionDocumentFAQ->setData(QString("%1/FAQ.html").arg(QApplication::applicationDirPath()));
405 actionDocumentChangelog->setData(QString("%1/Changelog.html").arg(QApplication::applicationDirPath()));
406 actionDocumentTranslate->setData(QString("%1/Translate.html").arg(QApplication::applicationDirPath()));
407 connect(actionCheckUpdates, SIGNAL(triggered()), this, SLOT(checkUpdatesActionActivated()));
408 connect(actionVisitHomepage, SIGNAL(triggered()), this, SLOT(visitHomepageActionActivated()));
409 connect(actionVisitSupport, SIGNAL(triggered()), this, SLOT(visitHomepageActionActivated()));
410 connect(actionDocumentFAQ, SIGNAL(triggered()), this, SLOT(documentActionActivated()));
411 connect(actionDocumentChangelog, SIGNAL(triggered()), this, SLOT(documentActionActivated()));
412 connect(actionDocumentTranslate, SIGNAL(triggered()), this, SLOT(documentActionActivated()));
414 //Center window in screen
415 QRect desktopRect = QApplication::desktop()->screenGeometry();
416 QRect thisRect = this->geometry();
417 move((desktopRect.width() - thisRect.width()) / 2, (desktopRect.height() - thisRect.height()) / 2);
418 setMinimumSize(thisRect.width(), thisRect.height());
420 //Create banner
421 m_banner = new WorkingBanner(this);
423 //Create DropBox widget
424 m_dropBox = new DropBox(this, m_fileListModel, m_settings);
425 connect(m_fileListModel, SIGNAL(modelReset()), m_dropBox, SLOT(modelChanged()));
426 connect(m_fileListModel, SIGNAL(rowsInserted(QModelIndex,int,int)), m_dropBox, SLOT(modelChanged()));
427 connect(m_fileListModel, SIGNAL(rowsRemoved(QModelIndex,int,int)), m_dropBox, SLOT(modelChanged()));
428 connect(m_fileListModel, SIGNAL(rowAppended()), m_dropBox, SLOT(modelChanged()));
430 //Create message handler thread
431 m_messageHandler = new MessageHandlerThread();
432 m_delayedFileList = new QStringList();
433 m_delayedFileTimer = new QTimer();
434 m_delayedFileTimer->setSingleShot(true);
435 m_delayedFileTimer->setInterval(5000);
436 connect(m_messageHandler, SIGNAL(otherInstanceDetected()), this, SLOT(notifyOtherInstance()), Qt::QueuedConnection);
437 connect(m_messageHandler, SIGNAL(fileReceived(QString)), this, SLOT(addFileDelayed(QString)), Qt::QueuedConnection);
438 connect(m_messageHandler, SIGNAL(folderReceived(QString, bool)), this, SLOT(addFolderDelayed(QString, bool)), Qt::QueuedConnection);
439 connect(m_messageHandler, SIGNAL(killSignalReceived()), this, SLOT(close()), Qt::QueuedConnection);
440 connect(m_delayedFileTimer, SIGNAL(timeout()), this, SLOT(handleDelayedFiles()));
441 m_messageHandler->start();
443 //Load translation file
444 QList<QAction*> languageActions = m_languageActionGroup->actions();
445 while(!languageActions.isEmpty())
447 QAction *currentLanguage = languageActions.takeFirst();
448 if(currentLanguage->data().toString().compare(m_settings->currentLanguage(), Qt::CaseInsensitive) == 0)
450 currentLanguage->setChecked(true);
451 languageActionActivated(currentLanguage);
455 //Re-translate (make sure we translate once)
456 QEvent languageChangeEvent(QEvent::LanguageChange);
457 changeEvent(&languageChangeEvent);
459 //Enable Drag & Drop
460 this->setAcceptDrops(true);
463 ////////////////////////////////////////////////////////////
464 // Destructor
465 ////////////////////////////////////////////////////////////
467 MainWindow::~MainWindow(void)
469 //Stop message handler thread
470 if(m_messageHandler && m_messageHandler->isRunning())
472 m_messageHandler->stop();
473 if(!m_messageHandler->wait(2500))
475 m_messageHandler->terminate();
476 m_messageHandler->wait();
480 //Unset models
481 SET_MODEL(sourceFileView, NULL);
482 SET_MODEL(outputFolderView, NULL);
483 SET_MODEL(metaDataView, NULL);
485 //Free memory
486 LAMEXP_DELETE(m_tabActionGroup);
487 LAMEXP_DELETE(m_styleActionGroup);
488 LAMEXP_DELETE(m_languageActionGroup);
489 LAMEXP_DELETE(m_banner);
490 LAMEXP_DELETE(m_fileSystemModel);
491 LAMEXP_DELETE(m_messageHandler);
492 LAMEXP_DELETE(m_delayedFileList);
493 LAMEXP_DELETE(m_delayedFileTimer);
494 LAMEXP_DELETE(m_metaInfoModel);
495 LAMEXP_DELETE(m_encoderButtonGroup);
496 LAMEXP_DELETE(m_encoderButtonGroup);
497 LAMEXP_DELETE(m_sourceFilesContextMenu);
498 LAMEXP_DELETE(m_outputFolderFavoritesMenu);
499 LAMEXP_DELETE(m_outputFolderContextMenu);
500 LAMEXP_DELETE(m_dropBox);
503 ////////////////////////////////////////////////////////////
504 // PRIVATE FUNCTIONS
505 ////////////////////////////////////////////////////////////
508 * Add file to source list
510 void MainWindow::addFiles(const QStringList &files)
512 if(files.isEmpty())
514 return;
517 tabWidget->setCurrentIndex(0);
519 int timeMT = 0, timeST = 0;
521 //--MT--
523 FileAnalyzer *analyzer = new FileAnalyzer(files);
524 connect(analyzer, SIGNAL(fileSelected(QString)), m_banner, SLOT(setText(QString)), Qt::QueuedConnection);
525 connect(analyzer, SIGNAL(progressValChanged(unsigned int)), m_banner, SLOT(setProgressVal(unsigned int)), Qt::QueuedConnection);
526 connect(analyzer, SIGNAL(progressMaxChanged(unsigned int)), m_banner, SLOT(setProgressMax(unsigned int)), Qt::QueuedConnection);
527 connect(analyzer, SIGNAL(fileAnalyzed(AudioFileModel)), m_fileListModel, SLOT(addFile(AudioFileModel)), Qt::QueuedConnection);
528 connect(m_banner, SIGNAL(userAbort()), analyzer, SLOT(abortProcess()), Qt::DirectConnection);
532 m_fileListModel->setBlockUpdates(true);
533 QTime startTime = QTime::currentTime();
534 m_banner->show(tr("Adding file(s), please wait..."), analyzer);
535 timeMT = startTime.secsTo(QTime::currentTime());
537 catch(...)
539 /* ignore any exceptions that may occur */
542 //--ST--
544 FileAnalyzer_ST *analyzerST = new FileAnalyzer_ST(files);
545 connect(analyzerST, SIGNAL(fileSelected(QString)), m_banner, SLOT(setText(QString)), Qt::QueuedConnection);
546 connect(analyzerST, SIGNAL(progressValChanged(unsigned int)), m_banner, SLOT(setProgressVal(unsigned int)), Qt::QueuedConnection);
547 connect(analyzerST, SIGNAL(progressMaxChanged(unsigned int)), m_banner, SLOT(setProgressMax(unsigned int)), Qt::QueuedConnection);
548 connect(analyzerST, SIGNAL(fileAnalyzed(AudioFileModel)), m_fileListModel, SLOT(addFile(AudioFileModel)), Qt::QueuedConnection);
549 connect(m_banner, SIGNAL(userAbort()), analyzerST, SLOT(abortProcess()), Qt::DirectConnection);
553 m_fileListModel->setBlockUpdates(true);
554 QTime startTime = QTime::currentTime();
555 m_banner->show(tr("Adding file(s), please wait..."), analyzerST);
556 timeST = startTime.secsTo(QTime::currentTime());
558 catch(...)
560 /* ignore any exceptions that may occur */
563 //------
565 double speedUp = static_cast<double>(timeST) / static_cast<double>(timeMT);
566 QMessageBox::information(this, "Speed Up", QString().sprintf("Announcement: The new multi-threaded file analyzer is %.1fx faster !!!", speedUp), QMessageBox::Ok);
567 qWarning("ST: %d, MT: %d", timeST, timeMT);
569 //------
571 m_fileListModel->setBlockUpdates(false);
572 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
573 sourceFileView->update();
574 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
575 sourceFileView->scrollToBottom();
576 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
578 if(analyzer->filesDenied())
580 QMessageBox::warning(this, tr("Access Denied"), QString("%1<br>%2").arg(NOBR(tr("%1 file(s) have been rejected, because read access was not granted!").arg(analyzer->filesDenied())), NOBR(tr("This usually means the file is locked by another process."))));
582 if(analyzer->filesDummyCDDA())
584 QMessageBox::warning(this, tr("CDDA Files"), QString("%1<br><br>%2<br>%3").arg(NOBR(tr("%1 file(s) have been rejected, because they are dummy CDDA files!").arg(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>"))));
586 if(analyzer->filesCueSheet())
588 QMessageBox::warning(this, tr("Cue Sheet"), QString("%1<br>%2").arg(NOBR(tr("%1 file(s) have been rejected, because they appear to be Cue Sheet images!").arg(analyzer->filesCueSheet())), NOBR(tr("Please use LameXP's Cue Sheet wizard for importing Cue Sheet files."))));
590 if(analyzer->filesRejected())
592 QMessageBox::warning(this, tr("Files Rejected"), QString("%1<br>%2").arg(NOBR(tr("%1 file(s) have been rejected, because the file format could not be recognized!").arg(analyzer->filesRejected())), NOBR(tr("This usually means the file is damaged or the file format is not supported."))));
595 LAMEXP_DELETE(analyzer);
596 LAMEXP_DELETE(analyzerST);
597 m_banner->close();
601 * Add folder to source list
603 void MainWindow::addFolder(const QString &path, bool recursive, bool delayed)
605 QFileInfoList folderInfoList;
606 folderInfoList << QFileInfo(path);
607 QStringList fileList;
609 m_banner->show(tr("Scanning folder(s) for files, please wait..."));
611 QApplication::processEvents();
612 GetAsyncKeyState(VK_ESCAPE);
614 while(!folderInfoList.isEmpty())
616 if(GetAsyncKeyState(VK_ESCAPE) & 0x0001)
618 MessageBeep(MB_ICONERROR);
619 qWarning("Operation cancelled by user!");
620 fileList.clear();
621 break;
624 QDir currentDir(folderInfoList.takeFirst().canonicalFilePath());
625 QFileInfoList fileInfoList = currentDir.entryInfoList(QDir::Files | QDir::NoSymLinks);
627 while(!fileInfoList.isEmpty())
629 fileList << fileInfoList.takeFirst().canonicalFilePath();
632 QApplication::processEvents();
634 if(recursive)
636 folderInfoList.append(currentDir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks));
637 QApplication::processEvents();
641 m_banner->close();
642 QApplication::processEvents();
644 if(!fileList.isEmpty())
646 if(delayed)
648 addFilesDelayed(fileList);
650 else
652 addFiles(fileList);
658 * Check for updates
660 bool MainWindow::checkForUpdates(void)
662 bool bReadyToInstall = false;
664 UpdateDialog *updateDialog = new UpdateDialog(m_settings, this);
665 updateDialog->exec();
667 if(updateDialog->getSuccess())
669 m_settings->autoUpdateLastCheck(QDate::currentDate().toString(Qt::ISODate));
670 bReadyToInstall = updateDialog->updateReadyToInstall();
673 LAMEXP_DELETE(updateDialog);
674 return bReadyToInstall;
677 void MainWindow::refreshFavorites(void)
679 QList<QAction*> folderList = m_outputFolderFavoritesMenu->actions();
680 QStringList favorites = m_settings->favoriteOutputFolders().split("|", QString::SkipEmptyParts);
681 while(favorites.count() > 6) favorites.removeFirst();
683 while(!folderList.isEmpty())
685 QAction *currentItem = folderList.takeFirst();
686 if(currentItem->isSeparator()) break;
687 m_outputFolderFavoritesMenu->removeAction(currentItem);
688 LAMEXP_DELETE(currentItem);
691 QAction *lastItem = m_outputFolderFavoritesMenu->actions().first();
693 while(!favorites.isEmpty())
695 QString path = favorites.takeLast();
696 if(QDir(path).exists())
698 QAction *action = new QAction(QIcon(":/icons/folder_go.png"), QDir::toNativeSeparators(path), this);
699 action->setData(path);
700 m_outputFolderFavoritesMenu->insertAction(lastItem, action);
701 connect(action, SIGNAL(triggered(bool)), this, SLOT(gotoFavoriteFolder()));
702 lastItem = action;
707 ////////////////////////////////////////////////////////////
708 // EVENTS
709 ////////////////////////////////////////////////////////////
712 * Window is about to be shown
714 void MainWindow::showEvent(QShowEvent *event)
716 m_accepted = false;
717 m_dropNoteLabel->setGeometry(0, 0, sourceFileView->width(), sourceFileView->height());
718 sourceModelChanged();
720 if(!event->spontaneous())
722 tabWidget->setCurrentIndex(0);
725 if(m_firstTimeShown)
727 m_firstTimeShown = false;
728 QTimer::singleShot(0, this, SLOT(windowShown()));
730 else
732 if(m_settings->dropBoxWidgetEnabled())
734 m_dropBox->setVisible(true);
740 * Re-translate the UI
742 void MainWindow::changeEvent(QEvent *e)
744 if(e->type() == QEvent::LanguageChange)
746 int comboBoxIndex[6];
748 //Backup combobox indices, as retranslateUi() resets
749 comboBoxIndex[0] = comboBoxMP3ChannelMode->currentIndex();
750 comboBoxIndex[1] = comboBoxSamplingRate->currentIndex();
751 comboBoxIndex[2] = comboBoxAACProfile->currentIndex();
752 comboBoxIndex[3] = comboBoxAftenCodingMode->currentIndex();
753 comboBoxIndex[4] = comboBoxAftenDRCMode->currentIndex();
754 comboBoxIndex[5] = comboBoxNormalizationMode->currentIndex();
756 //Re-translate from UIC
757 Ui::MainWindow::retranslateUi(this);
759 //Restore combobox indices
760 comboBoxMP3ChannelMode->setCurrentIndex(comboBoxIndex[0]);
761 comboBoxSamplingRate->setCurrentIndex(comboBoxIndex[1]);
762 comboBoxAACProfile->setCurrentIndex(comboBoxIndex[2]);
763 comboBoxAftenCodingMode->setCurrentIndex(comboBoxIndex[3]);
764 comboBoxAftenDRCMode->setCurrentIndex(comboBoxIndex[4]);
765 comboBoxNormalizationMode->setCurrentIndex(comboBoxIndex[5]);
767 //Update the window title
768 if(LAMEXP_DEBUG)
770 setWindowTitle(QString("%1 [!!! DEBUG BUILD !!!]").arg(windowTitle()));
772 else if(lamexp_version_demo())
774 setWindowTitle(QString("%1 [%2]").arg(windowTitle(), tr("DEMO VERSION")));
777 //Manually re-translate widgets that UIC doesn't handle
778 m_dropNoteLabel->setText(QString("» %1 «").arg(tr("You can drop in audio files here!")));
779 m_outputFolderNoteBox->setText(tr("Initializing directory outline, please be patient..."));
780 m_showDetailsContextAction->setText(tr("Show Details"));
781 m_previewContextAction->setText(tr("Open File in External Application"));
782 m_findFileContextAction->setText(tr("Browse File Location"));
783 m_showFolderContextAction->setText(tr("Browse Selected Folder"));
784 m_refreshFolderContextAction->setText(tr("Refresh Directory Outline"));
785 m_addFavoriteFolderAction->setText(tr("Bookmark Current Output Folder"));
786 m_exportCsvContextAction->setText(tr("Export Meta Tags to CSV File"));
787 m_importCsvContextAction->setText(tr("Import Meta Tags from CSV File"));
789 //Force GUI update
790 m_metaInfoModel->clearData();
791 m_metaInfoModel->setData(m_metaInfoModel->index(4, 1), m_settings->metaInfoPosition());
792 updateEncoder(m_settings->compressionEncoder());
793 updateLameAlgoQuality(sliderLameAlgoQuality->value());
794 updateMaximumInstances(sliderMaxInstances->value());
795 renameOutputPatternChanged(lineEditRenamePattern->text());
797 //Re-install shell integration
798 if(m_settings->shellIntegrationEnabled())
800 ShellIntegration::install();
803 //Force resize, if needed
804 tabPageChanged(tabWidget->currentIndex());
809 * File dragged over window
811 void MainWindow::dragEnterEvent(QDragEnterEvent *event)
813 QStringList formats = event->mimeData()->formats();
815 if(formats.contains("application/x-qt-windows-mime;value=\"FileNameW\"", Qt::CaseInsensitive) && formats.contains("text/uri-list", Qt::CaseInsensitive))
817 event->acceptProposedAction();
822 * File dropped onto window
824 void MainWindow::dropEvent(QDropEvent *event)
826 ABORT_IF_BUSY;
828 QStringList droppedFiles;
829 QList<QUrl> urls = event->mimeData()->urls();
831 while(!urls.isEmpty())
833 QUrl currentUrl = urls.takeFirst();
834 QFileInfo file(currentUrl.toLocalFile());
835 if(!file.exists())
837 continue;
839 if(file.isFile())
841 qDebug("Dropped File: %s", file.canonicalFilePath().toUtf8().constData());
842 droppedFiles << file.canonicalFilePath();
843 continue;
845 if(file.isDir())
847 qDebug("Dropped Folder: %s", file.canonicalFilePath().toUtf8().constData());
848 QList<QFileInfo> list = QDir(file.canonicalFilePath()).entryInfoList(QDir::Files | QDir::NoSymLinks);
849 if(list.count() > 0)
851 for(int j = 0; j < list.count(); j++)
853 droppedFiles << list.at(j).canonicalFilePath();
856 else
858 list = QDir(file.canonicalFilePath()).entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks);
859 for(int j = 0; j < list.count(); j++)
861 qDebug("Descending to Folder: %s", list.at(j).canonicalFilePath().toUtf8().constData());
862 urls.prepend(QUrl::fromLocalFile(list.at(j).canonicalFilePath()));
868 if(!droppedFiles.isEmpty())
870 addFilesDelayed(droppedFiles, true);
875 * Window tries to close
877 void MainWindow::closeEvent(QCloseEvent *event)
879 if(m_banner->isVisible() || m_delayedFileTimer->isActive())
881 MessageBeep(MB_ICONEXCLAMATION);
882 event->ignore();
885 if(m_dropBox)
887 m_dropBox->hide();
892 * Window was resized
894 void MainWindow::resizeEvent(QResizeEvent *event)
896 if(event) QMainWindow::resizeEvent(event);
897 m_dropNoteLabel->setGeometry(0, 0, sourceFileView->width(), sourceFileView->height());
899 if(QWidget *port = outputFolderView->viewport())
901 m_outputFolderNoteBox->setGeometry(16, (port->height() - 64) / 2, port->width() - 32, 64);
906 * Key press event filter
908 void MainWindow::keyPressEvent(QKeyEvent *e)
910 if(e->key() == Qt::Key_F5)
912 if(outputFolderView->isVisible())
914 QTimer::singleShot(0, this, SLOT(refreshFolderContextActionTriggered()));
915 return;
919 if(e->key() == Qt::Key_Delete)
921 if(sourceFileView->isVisible())
923 QTimer::singleShot(0, this, SLOT(removeFileButtonClicked()));
924 return;
928 QMainWindow::keyPressEvent(e);
932 * Event filter
934 bool MainWindow::eventFilter(QObject *obj, QEvent *event)
936 if(obj == m_fileSystemModel)
938 if(QApplication::overrideCursor() == NULL)
940 QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
941 QTimer::singleShot(250, this, SLOT(restoreCursor()));
944 else if(obj == outputFolderView)
946 switch(event->type())
948 case QEvent::Enter:
949 case QEvent::Leave:
950 case QEvent::KeyPress:
951 case QEvent::KeyRelease:
952 case QEvent::FocusIn:
953 case QEvent::FocusOut:
954 case QEvent::TouchEnd:
955 outputFolderViewClicked(outputFolderView->currentIndex());
956 break;
959 else if(obj == outputFolderLabel)
961 switch(event->type())
963 case QEvent::MouseButtonPress:
964 if(dynamic_cast<QMouseEvent*>(event)->button() == Qt::LeftButton)
966 QString path = outputFolderLabel->text();
967 if(!path.endsWith(QDir::separator())) path.append(QDir::separator());
968 ShellExecuteW(reinterpret_cast<HWND>(this->winId()), L"explore", QWCHAR(path), NULL, NULL, SW_SHOW);
970 break;
971 case QEvent::Enter:
972 outputFolderLabel->setForegroundRole(QPalette::Link);
973 break;
974 case QEvent::Leave:
975 outputFolderLabel->setForegroundRole(QPalette::WindowText);
976 break;
979 else if(obj == outputFoldersFovoritesLabel)
981 QMouseEvent *mouseEvent = dynamic_cast<QMouseEvent*>(event);
982 QPoint pos = (mouseEvent != NULL) ? mouseEvent->pos() : QPoint();
983 QWidget *sender = dynamic_cast<QLabel*>(obj);
985 switch(event->type())
987 case QEvent::Enter:
988 outputFoldersFovoritesLabel->setFrameShadow(QFrame::Raised);
989 break;
990 case QEvent::MouseButtonPress:
991 outputFoldersFovoritesLabel->setFrameShadow(QFrame::Sunken);
992 break;
993 case QEvent::MouseButtonRelease:
994 outputFoldersFovoritesLabel->setFrameShadow(QFrame::Raised);
995 if(sender && mouseEvent)
997 if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0 && mouseEvent->button() != Qt::MidButton)
999 if(outputFolderView->isEnabled())
1001 m_outputFolderFavoritesMenu->popup(sender->mapToGlobal(pos));
1005 break;
1006 case QEvent::Leave:
1007 outputFoldersFovoritesLabel->setFrameShadow(QFrame::Plain);
1008 break;
1011 else if(obj == outputFoldersEditorLabel)
1013 QMouseEvent *mouseEvent = dynamic_cast<QMouseEvent*>(event);
1014 QPoint pos = (mouseEvent != NULL) ? mouseEvent->pos() : QPoint();
1015 QWidget *sender = dynamic_cast<QLabel*>(obj);
1017 switch(event->type())
1019 case QEvent::Enter:
1020 outputFoldersEditorLabel->setFrameShadow(QFrame::Raised);
1021 break;
1022 case QEvent::MouseButtonPress:
1023 outputFoldersEditorLabel->setFrameShadow(QFrame::Sunken);
1024 break;
1025 case QEvent::MouseButtonRelease:
1026 outputFoldersEditorLabel->setFrameShadow(QFrame::Raised);
1027 if(sender && mouseEvent)
1029 if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0 && mouseEvent->button() != Qt::MidButton)
1031 if(outputFolderView->isEnabled())
1033 outputFolderView->setEnabled(false);
1034 outputFolderLabel->setVisible(false);
1035 outputFolderEdit->setVisible(true);
1036 outputFolderEdit->setText(outputFolderLabel->text());
1037 outputFolderEdit->selectAll();
1038 outputFolderEdit->setFocus();
1042 break;
1043 case QEvent::Leave:
1044 outputFoldersEditorLabel->setFrameShadow(QFrame::Plain);
1045 break;
1049 return QMainWindow::eventFilter(obj, event);
1052 bool MainWindow::event(QEvent *e)
1054 switch(e->type())
1056 case lamexp_event_queryendsession:
1057 qWarning("System is shutting down, main window prepares to close...");
1058 if(m_banner->isVisible()) m_banner->close();
1059 if(m_delayedFileTimer->isActive()) m_delayedFileTimer->stop();
1060 return true;
1061 case lamexp_event_endsession:
1062 qWarning("System is shutting down, main window will close now...");
1063 if(isVisible())
1065 while(!close())
1067 QApplication::processEvents(QEventLoop::WaitForMoreEvents & QEventLoop::ExcludeUserInputEvents);
1070 m_fileListModel->clearFiles();
1071 return true;
1072 case QEvent::MouseButtonPress:
1073 if(outputFolderEdit->isVisible())
1075 QTimer::singleShot(0, this, SLOT(outputFolderEditFinished()));
1077 default:
1078 return QMainWindow::event(e);
1082 bool MainWindow::winEvent(MSG *message, long *result)
1084 return WinSevenTaskbar::handleWinEvent(message, result);
1087 ////////////////////////////////////////////////////////////
1088 // Slots
1089 ////////////////////////////////////////////////////////////
1091 // =========================================================
1092 // Show window slots
1093 // =========================================================
1096 * Window shown
1098 void MainWindow::windowShown(void)
1100 QStringList arguments = QApplication::arguments();
1102 //First run?
1103 bool firstRun = false;
1104 for(int i = 0; i < arguments.count(); i++)
1106 if(!arguments[i].compare("--first-run", Qt::CaseInsensitive)) firstRun = true;
1109 //Check license
1110 if((m_settings->licenseAccepted() <= 0) || firstRun)
1112 int iAccepted = -1;
1114 if((m_settings->licenseAccepted() == 0) || firstRun)
1116 AboutDialog *about = new AboutDialog(m_settings, this, true);
1117 iAccepted = about->exec();
1118 LAMEXP_DELETE(about);
1121 if(iAccepted <= 0)
1123 m_settings->licenseAccepted(-1);
1124 QApplication::processEvents();
1125 PlaySound(MAKEINTRESOURCE(IDR_WAVE_WHAMMY), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
1126 QMessageBox::critical(this, tr("License Declined"), tr("You have declined the license. Consequently the application will exit now!"), tr("Goodbye!"));
1127 QFileInfo uninstallerInfo = QFileInfo(QString("%1/Uninstall.exe").arg(QApplication::applicationDirPath()));
1128 if(uninstallerInfo.exists())
1130 QString uninstallerDir = uninstallerInfo.canonicalPath();
1131 QString uninstallerPath = uninstallerInfo.canonicalFilePath();
1132 for(int i = 0; i < 3; i++)
1134 HINSTANCE res = ShellExecuteW(reinterpret_cast<HWND>(this->winId()), L"open", QWCHAR(QDir::toNativeSeparators(uninstallerPath)), L"/Force", QWCHAR(QDir::toNativeSeparators(uninstallerDir)), SW_SHOWNORMAL);
1135 if(reinterpret_cast<int>(res) > 32) break;
1138 else
1140 MoveFileEx(QWCHAR(QDir::toNativeSeparators(QFileInfo(QApplication::applicationFilePath()).canonicalFilePath())), NULL, MOVEFILE_DELAY_UNTIL_REBOOT | MOVEFILE_REPLACE_EXISTING);
1142 QApplication::quit();
1143 return;
1146 PlaySound(MAKEINTRESOURCE(IDR_WAVE_WOOHOO), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
1147 m_settings->licenseAccepted(1);
1148 if(lamexp_version_demo()) showAnnounceBox();
1151 //Check for expiration
1152 if(lamexp_version_demo())
1154 if(QDate::currentDate() >= lamexp_version_expires())
1156 qWarning("Binary has expired !!!");
1157 PlaySound(MAKEINTRESOURCE(IDR_WAVE_WHAMMY), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
1158 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)
1160 checkForUpdates();
1162 QApplication::quit();
1163 return;
1167 //Slow startup indicator
1168 if(m_settings->slowStartup() && m_settings->antivirNotificationsEnabled())
1170 QString message;
1171 message += NOBR(tr("It seems that a bogus anti-virus software is slowing down the startup of LameXP.")).append("<br>");
1172 message += NOBR(tr("Please refer to the %1 document for details and solutions!")).arg("<a href=\"http://lamexp.git.sourceforge.net/git/gitweb.cgi?p=lamexp/lamexp;a=blob_plain;f=doc/FAQ.html;hb=HEAD#df406578\">F.A.Q.</a>").append("<br>");
1173 if(QMessageBox::warning(this, tr("Slow Startup"), message, tr("Discard"), tr("Don't Show Again")) == 1)
1175 m_settings->antivirNotificationsEnabled(false);
1176 actionDisableSlowStartupNotifications->setChecked(!m_settings->antivirNotificationsEnabled());
1180 //Update reminder
1181 if(QDate::currentDate() >= lamexp_version_date().addYears(1))
1183 qWarning("Binary is more than a year old, time to update!");
1184 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"));
1185 switch(ret)
1187 case 0:
1188 if(checkForUpdates())
1190 QApplication::quit();
1191 return;
1193 break;
1194 case 1:
1195 QApplication::quit();
1196 return;
1197 default:
1198 QEventLoop loop; QTimer::singleShot(7000, &loop, SLOT(quit()));
1199 PlaySound(MAKEINTRESOURCE(IDR_WAVE_WAITING), GetModuleHandle(NULL), SND_RESOURCE | SND_ASYNC);
1200 m_banner->show(tr("Skipping update check this time, please be patient..."), &loop);
1201 break;
1204 else if(m_settings->autoUpdateEnabled())
1206 QDate lastUpdateCheck = QDate::fromString(m_settings->autoUpdateLastCheck(), Qt::ISODate);
1207 if(!firstRun && (!lastUpdateCheck.isValid() || QDate::currentDate() >= lastUpdateCheck.addDays(14)))
1209 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)
1211 if(checkForUpdates())
1213 QApplication::quit();
1214 return;
1220 //Check for AAC support
1221 if(m_neroEncoderAvailable)
1223 if(m_settings->neroAacNotificationsEnabled())
1225 if(lamexp_tool_version("neroAacEnc.exe") < lamexp_toolver_neroaac())
1227 QString messageText;
1228 messageText += NOBR(tr("LameXP detected that your version of the Nero AAC encoder is outdated!")).append("<br>");
1229 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>");
1230 messageText += NOBR(tr("You can download the latest version of the Nero AAC encoder from the Nero website at:")).append("<br>");
1231 messageText += "<nobr><tt>" + LINK(AboutDialog::neroAacUrl) + "</tt></nobr><br><br>";
1232 messageText += NOBR(tr("(Hint: Please ignore the name of the downloaded ZIP file and check the included 'changelog.txt' instead!)")).append("<br>");
1233 QMessageBox::information(this, tr("AAC Encoder Outdated"), messageText);
1237 else
1239 if(m_settings->neroAacNotificationsEnabled() && (!(m_fhgEncoderAvailable || m_qaacEncoderAvailable)))
1241 QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
1242 if(appPath.isEmpty()) appPath = QCoreApplication::applicationDirPath();
1243 QString messageText;
1244 messageText += NOBR(tr("The Nero AAC encoder could not be found. AAC encoding support will be disabled.")).append("<br>");
1245 messageText += NOBR(tr("Please put 'neroAacEnc.exe', 'neroAacDec.exe' and 'neroAacTag.exe' into the LameXP directory!")).append("<br><br>");
1246 messageText += NOBR(tr("Your LameXP directory is located here:")).append("<br>");
1247 messageText += QString("<nobr><tt>%1</tt></nobr><br><br>").arg(FSLINK(QDir::toNativeSeparators(appPath)));
1248 messageText += NOBR(tr("You can download the Nero AAC encoder for free from the official Nero website at:")).append("<br>");
1249 messageText += "<nobr><tt>" + LINK(AboutDialog::neroAacUrl) + "</tt></nobr><br>";
1250 if(QMessageBox::information(this, tr("AAC Support Disabled"), messageText, tr("Discard"), tr("Don't Show Again")) == 1)
1252 m_settings->neroAacNotificationsEnabled(false);
1253 actionDisableNeroAacNotifications->setChecked(!m_settings->neroAacNotificationsEnabled());
1258 //Add files from the command-line
1259 for(int i = 0; i < arguments.count() - 1; i++)
1261 QStringList addedFiles;
1262 if(!arguments[i].compare("--add", Qt::CaseInsensitive))
1264 QFileInfo currentFile(arguments[++i].trimmed());
1265 qDebug("Adding file from CLI: %s", currentFile.absoluteFilePath().toUtf8().constData());
1266 addedFiles.append(currentFile.absoluteFilePath());
1268 if(!addedFiles.isEmpty())
1270 addFilesDelayed(addedFiles);
1274 //Add folders from the command-line
1275 for(int i = 0; i < arguments.count() - 1; i++)
1277 if(!arguments[i].compare("--add-folder", Qt::CaseInsensitive))
1279 QFileInfo currentFile(arguments[++i].trimmed());
1280 qDebug("Adding folder from CLI: %s", currentFile.absoluteFilePath().toUtf8().constData());
1281 addFolder(currentFile.absoluteFilePath(), false, true);
1283 if(!arguments[i].compare("--add-recursive", Qt::CaseInsensitive))
1285 QFileInfo currentFile(arguments[++i].trimmed());
1286 qDebug("Adding folder recursively from CLI: %s", currentFile.absoluteFilePath().toUtf8().constData());
1287 addFolder(currentFile.absoluteFilePath(), true, true);
1291 //Enable shell integration
1292 if(m_settings->shellIntegrationEnabled())
1294 ShellIntegration::install();
1297 //Make DropBox visible
1298 if(m_settings->dropBoxWidgetEnabled())
1300 m_dropBox->setVisible(true);
1305 * Show announce box
1307 void MainWindow::showAnnounceBox(void)
1309 const unsigned int timeout = 8U;
1311 const QString announceText = QString("%1<br><br>%2<br><nobr><tt>%3</tt></nobr><br>").arg
1313 NOBR("We are still looking for LameXP translators!"),
1314 NOBR("If you are willing to translate LameXP to your language or to complete an existing translation, please refer to:"),
1315 LINK("http://mulder.brhack.net/public/doc/lamexp_translate.html")
1318 QMessageBox *announceBox = new QMessageBox(QMessageBox::Warning, "We want you!", announceText, QMessageBox::NoButton, this);
1319 announceBox->setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
1320 announceBox->setIconPixmap(QIcon(":/images/Announcement.png").pixmap(64,79));
1322 QTimer *timers[timeout+1];
1323 QPushButton *buttons[timeout+1];
1325 for(unsigned int i = 0; i <= timeout; i++)
1327 QString text = (i > 0) ? QString("%1 (%2)").arg(tr("Discard"), QString::number(i)) : tr("Discard");
1328 buttons[i] = announceBox->addButton(text, (i > 0) ? QMessageBox::NoRole : QMessageBox::AcceptRole);
1331 for(unsigned int i = 0; i <= timeout; i++)
1333 buttons[i]->setEnabled(i == 0);
1334 buttons[i]->setVisible(i == timeout);
1337 for(unsigned int i = 0; i < timeout; i++)
1339 timers[i] = new QTimer(this);
1340 timers[i]->setSingleShot(true);
1341 timers[i]->setInterval(1000);
1342 connect(timers[i], SIGNAL(timeout()), buttons[i+1], SLOT(hide()));
1343 connect(timers[i], SIGNAL(timeout()), buttons[i], SLOT(show()));
1344 if(i > 0)
1346 connect(timers[i], SIGNAL(timeout()), timers[i-1], SLOT(start()));
1350 timers[timeout-1]->start();
1351 announceBox->exec();
1353 for(unsigned int i = 0; i < timeout; i++)
1355 timers[i]->stop();
1356 LAMEXP_DELETE(timers[i]);
1359 LAMEXP_DELETE(announceBox);
1362 // =========================================================
1363 // Main button solots
1364 // =========================================================
1367 * Encode button
1369 void MainWindow::encodeButtonClicked(void)
1371 static const unsigned __int64 oneGigabyte = 1073741824ui64;
1372 static const unsigned __int64 minimumFreeDiskspaceMultiplier = 2ui64;
1373 static const char *writeTestBuffer = "LAMEXP_WRITE_TEST";
1375 ABORT_IF_BUSY;
1377 if(m_fileListModel->rowCount() < 1)
1379 QMessageBox::warning(this, tr("LameXP"), NOBR(tr("You must add at least one file to the list before proceeding!")));
1380 tabWidget->setCurrentIndex(0);
1381 return;
1384 QString tempFolder = m_settings->customTempPathEnabled() ? m_settings->customTempPath() : lamexp_temp_folder2();
1385 if(!QFileInfo(tempFolder).exists() || !QFileInfo(tempFolder).isDir())
1387 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)
1389 while(checkBoxUseSystemTempFolder->isChecked() == m_settings->customTempPathEnabledDefault()) checkBoxUseSystemTempFolder->click();
1391 return;
1394 bool ok = false;
1395 unsigned __int64 currentFreeDiskspace = lamexp_free_diskspace(tempFolder, &ok);
1397 if(ok && (currentFreeDiskspace < (oneGigabyte * minimumFreeDiskspaceMultiplier)))
1399 QStringList tempFolderParts = tempFolder.split("/", QString::SkipEmptyParts, Qt::CaseInsensitive);
1400 tempFolderParts.takeLast();
1401 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_WHAMMY), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
1402 QString lowDiskspaceMsg = QString("%1<br>%2<br><br>%3<br>%4<br>").arg
1404 NOBR(tr("There are less than %1 GB of free diskspace available on your system's TEMP folder.").arg(QString::number(minimumFreeDiskspaceMultiplier))),
1405 NOBR(tr("It is highly recommend to free up more diskspace before proceeding with the encode!")),
1406 NOBR(tr("Your TEMP folder is located at:")),
1407 QString("<nobr><tt>%1</tt></nobr>").arg(FSLINK(tempFolderParts.join("\\")))
1409 switch(QMessageBox::warning(this, tr("Low Diskspace Warning"), lowDiskspaceMsg, tr("Abort Encoding Process"), tr("Clean Disk Now"), tr("Ignore")))
1411 case 1:
1412 QProcess::startDetached(QString("%1/cleanmgr.exe").arg(lamexp_known_folder(lamexp_folder_systemfolder)), QStringList() << "/D" << tempFolderParts.first());
1413 case 0:
1414 return;
1415 break;
1416 default:
1417 QMessageBox::warning(this, tr("Low Diskspace"), NOBR(tr("You are proceeding with low diskspace. Problems might occur!")));
1418 break;
1422 switch(m_settings->compressionEncoder())
1424 case SettingsModel::MP3Encoder:
1425 case SettingsModel::VorbisEncoder:
1426 case SettingsModel::AACEncoder:
1427 case SettingsModel::AC3Encoder:
1428 case SettingsModel::FLACEncoder:
1429 case SettingsModel::DCAEncoder:
1430 case SettingsModel::PCMEncoder:
1431 break;
1432 default:
1433 QMessageBox::warning(this, tr("LameXP"), tr("Sorry, an unsupported encoder has been chosen!"));
1434 tabWidget->setCurrentIndex(3);
1435 return;
1438 if(!m_settings->outputToSourceDir())
1440 QFile writeTest(QString("%1/~%2.txt").arg(m_settings->outputDir(), lamexp_rand_str()));
1441 if(!(writeTest.open(QIODevice::ReadWrite) && (writeTest.write(writeTestBuffer) == strlen(writeTestBuffer))))
1443 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!")));
1444 tabWidget->setCurrentIndex(1);
1445 return;
1447 else
1449 writeTest.close();
1450 writeTest.remove();
1454 m_accepted = true;
1455 close();
1459 * About button
1461 void MainWindow::aboutButtonClicked(void)
1463 ABORT_IF_BUSY;
1465 TEMP_HIDE_DROPBOX
1467 AboutDialog *aboutBox = new AboutDialog(m_settings, this);
1468 aboutBox->exec();
1469 LAMEXP_DELETE(aboutBox);
1474 * Close button
1476 void MainWindow::closeButtonClicked(void)
1478 ABORT_IF_BUSY;
1479 close();
1482 // =========================================================
1483 // Tab widget slots
1484 // =========================================================
1487 * Tab page changed
1489 void MainWindow::tabPageChanged(int idx)
1491 resizeEvent(NULL);
1493 QList<QAction*> actions = m_tabActionGroup->actions();
1494 for(int i = 0; i < actions.count(); i++)
1496 bool ok = false;
1497 int actionIndex = actions.at(i)->data().toInt(&ok);
1498 if(ok && actionIndex == idx)
1500 actions.at(i)->setChecked(true);
1504 int initialWidth = this->width();
1505 int maximumWidth = QApplication::desktop()->width();
1507 if(this->isVisible())
1509 while(tabWidget->width() < tabWidget->sizeHint().width())
1511 int previousWidth = this->width();
1512 this->resize(this->width() + 1, this->height());
1513 if(this->frameGeometry().width() >= maximumWidth) break;
1514 if(this->width() <= previousWidth) break;
1518 if(idx == tabWidget->indexOf(tabOptions) && scrollArea->widget() && this->isVisible())
1520 for(int i = 0; i < 2; i++)
1522 QApplication::processEvents();
1523 while(scrollArea->viewport()->width() < scrollArea->widget()->width())
1525 int previousWidth = this->width();
1526 this->resize(this->width() + 1, this->height());
1527 if(this->frameGeometry().width() >= maximumWidth) break;
1528 if(this->width() <= previousWidth) break;
1532 else if(idx == tabWidget->indexOf(tabSourceFiles))
1534 m_dropNoteLabel->setGeometry(0, 0, sourceFileView->width(), sourceFileView->height());
1536 else if(idx == tabWidget->indexOf(tabOutputDir))
1538 if(!m_fileSystemModel)
1540 QTimer::singleShot(125, this, SLOT(initOutputFolderModel()));
1542 else
1544 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
1548 if(initialWidth < this->width())
1550 QPoint prevPos = this->pos();
1551 int delta = (this->width() - initialWidth) >> 2;
1552 move(prevPos.x() - delta, prevPos.y());
1557 * Tab action triggered
1559 void MainWindow::tabActionActivated(QAction *action)
1561 if(action && action->data().isValid())
1563 bool ok = false;
1564 int index = action->data().toInt(&ok);
1565 if(ok)
1567 tabWidget->setCurrentIndex(index);
1572 // =========================================================
1573 // View menu slots
1574 // =========================================================
1577 * Style action triggered
1579 void MainWindow::styleActionActivated(QAction *action)
1581 //Change style setting
1582 if(action && action->data().isValid())
1584 bool ok = false;
1585 int actionIndex = action->data().toInt(&ok);
1586 if(ok)
1588 m_settings->interfaceStyle(actionIndex);
1592 //Set up the new style
1593 switch(m_settings->interfaceStyle())
1595 case 1:
1596 if(actionStyleCleanlooks->isEnabled())
1598 actionStyleCleanlooks->setChecked(true);
1599 QApplication::setStyle(new QCleanlooksStyle());
1600 break;
1602 case 2:
1603 if(actionStyleWindowsVista->isEnabled())
1605 actionStyleWindowsVista->setChecked(true);
1606 QApplication::setStyle(new QWindowsVistaStyle());
1607 break;
1609 case 3:
1610 if(actionStyleWindowsXP->isEnabled())
1612 actionStyleWindowsXP->setChecked(true);
1613 QApplication::setStyle(new QWindowsXPStyle());
1614 break;
1616 case 4:
1617 if(actionStyleWindowsClassic->isEnabled())
1619 actionStyleWindowsClassic->setChecked(true);
1620 QApplication::setStyle(new QWindowsStyle());
1621 break;
1623 default:
1624 actionStylePlastique->setChecked(true);
1625 QApplication::setStyle(new QPlastiqueStyle());
1626 break;
1629 //Force re-translate after style change
1630 if(QEvent *e = new QEvent(QEvent::LanguageChange))
1632 changeEvent(e);
1633 LAMEXP_DELETE(e);
1638 * Language action triggered
1640 void MainWindow::languageActionActivated(QAction *action)
1642 if(action->data().type() == QVariant::String)
1644 QString langId = action->data().toString();
1646 if(lamexp_install_translator(langId))
1648 action->setChecked(true);
1649 m_settings->currentLanguage(langId);
1655 * Load language from file action triggered
1657 void MainWindow::languageFromFileActionActivated(bool checked)
1659 QFileDialog dialog(this, tr("Load Translation"));
1660 dialog.setFileMode(QFileDialog::ExistingFile);
1661 dialog.setNameFilter(QString("%1 (*.qm)").arg(tr("Translation Files")));
1663 if(dialog.exec())
1665 QStringList selectedFiles = dialog.selectedFiles();
1666 if(lamexp_install_translator_from_file(selectedFiles.first()))
1668 QList<QAction*> actions = m_languageActionGroup->actions();
1669 while(!actions.isEmpty())
1671 actions.takeFirst()->setChecked(false);
1674 else
1676 languageActionActivated(m_languageActionGroup->actions().first());
1681 // =========================================================
1682 // Tools menu slots
1683 // =========================================================
1686 * Disable update reminder action
1688 void MainWindow::disableUpdateReminderActionTriggered(bool checked)
1690 if(checked)
1692 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))
1694 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!"))));
1695 m_settings->autoUpdateEnabled(false);
1697 else
1699 m_settings->autoUpdateEnabled(true);
1702 else
1704 QMessageBox::information(this, tr("Update Reminder"), NOBR(tr("The update reminder has been re-enabled.")));
1705 m_settings->autoUpdateEnabled(true);
1708 actionDisableUpdateReminder->setChecked(!m_settings->autoUpdateEnabled());
1712 * Disable sound effects action
1714 void MainWindow::disableSoundsActionTriggered(bool checked)
1716 if(checked)
1718 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))
1720 QMessageBox::information(this, tr("Sound Effects"), NOBR(tr("All sound effects have been disabled.")));
1721 m_settings->soundsEnabled(false);
1723 else
1725 m_settings->soundsEnabled(true);
1728 else
1730 QMessageBox::information(this, tr("Sound Effects"), NOBR(tr("The sound effects have been re-enabled.")));
1731 m_settings->soundsEnabled(true);
1734 actionDisableSounds->setChecked(!m_settings->soundsEnabled());
1738 * Disable Nero AAC encoder action
1740 void MainWindow::disableNeroAacNotificationsActionTriggered(bool checked)
1742 if(checked)
1744 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))
1746 QMessageBox::information(this, tr("Nero AAC Notifications"), NOBR(tr("All Nero AAC Encoder notifications have been disabled.")));
1747 m_settings->neroAacNotificationsEnabled(false);
1749 else
1751 m_settings->neroAacNotificationsEnabled(true);
1754 else
1756 QMessageBox::information(this, tr("Nero AAC Notifications"), NOBR(tr("The Nero AAC Encoder notifications have been re-enabled.")));
1757 m_settings->neroAacNotificationsEnabled(true);
1760 actionDisableNeroAacNotifications->setChecked(!m_settings->neroAacNotificationsEnabled());
1764 * Disable slow startup action
1766 void MainWindow::disableSlowStartupNotificationsActionTriggered(bool checked)
1768 if(checked)
1770 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))
1772 QMessageBox::information(this, tr("Slow Startup Notifications"), NOBR(tr("The slow startup notifications have been disabled.")));
1773 m_settings->antivirNotificationsEnabled(false);
1775 else
1777 m_settings->antivirNotificationsEnabled(true);
1780 else
1782 QMessageBox::information(this, tr("Slow Startup Notifications"), NOBR(tr("The slow startup notifications have been re-enabled.")));
1783 m_settings->antivirNotificationsEnabled(true);
1786 actionDisableSlowStartupNotifications->setChecked(!m_settings->antivirNotificationsEnabled());
1790 * Import a Cue Sheet file
1792 void MainWindow::importCueSheetActionTriggered(bool checked)
1794 ABORT_IF_BUSY;
1796 TEMP_HIDE_DROPBOX
1798 while(true)
1800 int result = 0;
1801 QString selectedCueFile;
1803 if(USE_NATIVE_FILE_DIALOG)
1805 selectedCueFile = QFileDialog::getOpenFileName(this, tr("Open Cue Sheet"), m_settings->mostRecentInputPath(), QString("%1 (*.cue)").arg(tr("Cue Sheet File")));
1807 else
1809 QFileDialog dialog(this, tr("Open Cue Sheet"));
1810 dialog.setFileMode(QFileDialog::ExistingFile);
1811 dialog.setNameFilter(QString("%1 (*.cue)").arg(tr("Cue Sheet File")));
1812 dialog.setDirectory(m_settings->mostRecentInputPath());
1813 if(dialog.exec())
1815 selectedCueFile = dialog.selectedFiles().first();
1819 if(!selectedCueFile.isEmpty())
1821 m_settings->mostRecentInputPath(QFileInfo(selectedCueFile).canonicalPath());
1822 CueImportDialog *cueImporter = new CueImportDialog(this, m_fileListModel, selectedCueFile);
1823 result = cueImporter->exec();
1824 LAMEXP_DELETE(cueImporter);
1827 if(result != (-1)) break;
1833 * Show the "drop box" widget
1835 void MainWindow::showDropBoxWidgetActionTriggered(bool checked)
1837 m_settings->dropBoxWidgetEnabled(true);
1839 if(!m_dropBox->isVisible())
1841 m_dropBox->show();
1844 lamexp_blink_window(m_dropBox);
1848 * Check for beta (pre-release) updates
1850 void MainWindow::checkForBetaUpdatesActionTriggered(bool checked)
1852 bool checkUpdatesNow = false;
1854 if(checked)
1856 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))
1858 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")))
1860 checkUpdatesNow = true;
1862 m_settings->autoUpdateCheckBeta(true);
1864 else
1866 m_settings->autoUpdateCheckBeta(false);
1869 else
1871 QMessageBox::information(this, tr("Beta Updates"), NOBR(tr("LameXP will <i>not</i> check for Beta (pre-release) updates from now on.")));
1872 m_settings->autoUpdateCheckBeta(false);
1875 actionCheckForBetaUpdates->setChecked(m_settings->autoUpdateCheckBeta());
1877 if(checkUpdatesNow)
1879 if(checkForUpdates())
1881 QApplication::quit();
1887 * Hibernate computer action
1889 void MainWindow::hibernateComputerActionTriggered(bool checked)
1891 if(checked)
1893 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))
1895 QMessageBox::information(this, tr("Hibernate Computer"), NOBR(tr("LameXP will hibernate the computer on shutdown from now on.")));
1896 m_settings->hibernateComputer(true);
1898 else
1900 m_settings->hibernateComputer(false);
1903 else
1905 QMessageBox::information(this, tr("Hibernate Computer"), NOBR(tr("LameXP will <i>not</i> hibernate the computer on shutdown from now on.")));
1906 m_settings->hibernateComputer(false);
1909 actionHibernateComputer->setChecked(m_settings->hibernateComputer());
1913 * Disable shell integration action
1915 void MainWindow::disableShellIntegrationActionTriggered(bool checked)
1917 if(checked)
1919 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))
1921 ShellIntegration::remove();
1922 QMessageBox::information(this, tr("Shell Integration"), NOBR(tr("The LameXP shell integration has been disabled.")));
1923 m_settings->shellIntegrationEnabled(false);
1925 else
1927 m_settings->shellIntegrationEnabled(true);
1930 else
1932 ShellIntegration::install();
1933 QMessageBox::information(this, tr("Shell Integration"), NOBR(tr("The LameXP shell integration has been re-enabled.")));
1934 m_settings->shellIntegrationEnabled(true);
1937 actionDisableShellIntegration->setChecked(!m_settings->shellIntegrationEnabled());
1939 if(lamexp_portable_mode() && actionDisableShellIntegration->isChecked())
1941 actionDisableShellIntegration->setEnabled(false);
1945 // =========================================================
1946 // Help menu slots
1947 // =========================================================
1950 * Visit homepage action
1952 void MainWindow::visitHomepageActionActivated(void)
1954 if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
1956 if(action->data().isValid() && (action->data().type() == QVariant::String))
1958 QDesktopServices::openUrl(QUrl(action->data().toString()));
1964 * Show document
1966 void MainWindow::documentActionActivated(void)
1968 if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
1970 if(action->data().isValid() && (action->data().type() == QVariant::String))
1972 QFileInfo document(action->data().toString());
1973 QFileInfo resource(QString(":/doc/%1.html").arg(document.baseName()));
1974 if(document.exists() && document.isFile() && (document.size() == resource.size()))
1976 QDesktopServices::openUrl(QUrl::fromLocalFile(document.canonicalFilePath()));
1978 else
1980 QFile source(resource.filePath());
1981 QFile output(QString("%1/%2.%3.html").arg(lamexp_temp_folder2(), document.baseName(), lamexp_rand_str().left(8)));
1982 if(source.open(QIODevice::ReadOnly) && output.open(QIODevice::ReadWrite))
1984 output.write(source.readAll());
1985 action->setData(output.fileName());
1986 source.close();
1987 output.close();
1988 QDesktopServices::openUrl(QUrl::fromLocalFile(output.fileName()));
1996 * Check for updates action
1998 void MainWindow::checkUpdatesActionActivated(void)
2000 ABORT_IF_BUSY;
2001 bool bFlag = false;
2003 TEMP_HIDE_DROPBOX
2005 bFlag = checkForUpdates();
2008 if(bFlag)
2010 QApplication::quit();
2014 // =========================================================
2015 // Source file slots
2016 // =========================================================
2019 * Add file(s) button
2021 void MainWindow::addFilesButtonClicked(void)
2023 ABORT_IF_BUSY;
2025 TEMP_HIDE_DROPBOX
2027 if(USE_NATIVE_FILE_DIALOG)
2029 QStringList fileTypeFilters = DecoderRegistry::getSupportedTypes();
2030 QStringList selectedFiles = QFileDialog::getOpenFileNames(this, tr("Add file(s)"), m_settings->mostRecentInputPath(), fileTypeFilters.join(";;"));
2031 if(!selectedFiles.isEmpty())
2033 m_settings->mostRecentInputPath(QFileInfo(selectedFiles.first()).canonicalPath());
2034 addFiles(selectedFiles);
2037 else
2039 QFileDialog dialog(this, tr("Add file(s)"));
2040 QStringList fileTypeFilters = DecoderRegistry::getSupportedTypes();
2041 dialog.setFileMode(QFileDialog::ExistingFiles);
2042 dialog.setNameFilter(fileTypeFilters.join(";;"));
2043 dialog.setDirectory(m_settings->mostRecentInputPath());
2044 if(dialog.exec())
2046 QStringList selectedFiles = dialog.selectedFiles();
2047 if(!selectedFiles.isEmpty())
2049 m_settings->mostRecentInputPath(QFileInfo(selectedFiles.first()).canonicalPath());
2050 addFiles(selectedFiles);
2058 * Open folder action
2060 void MainWindow::openFolderActionActivated(void)
2062 ABORT_IF_BUSY;
2063 QString selectedFolder;
2065 if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
2067 TEMP_HIDE_DROPBOX
2069 if(USE_NATIVE_FILE_DIALOG)
2071 selectedFolder = QFileDialog::getExistingDirectory(this, tr("Add Folder"), m_settings->mostRecentInputPath());
2073 else
2075 QFileDialog dialog(this, tr("Add Folder"));
2076 dialog.setFileMode(QFileDialog::DirectoryOnly);
2077 dialog.setDirectory(m_settings->mostRecentInputPath());
2078 if(dialog.exec())
2080 selectedFolder = dialog.selectedFiles().first();
2084 if(!selectedFolder.isEmpty())
2086 m_settings->mostRecentInputPath(QDir(selectedFolder).canonicalPath());
2087 addFolder(selectedFolder, action->data().toBool());
2094 * Remove file button
2096 void MainWindow::removeFileButtonClicked(void)
2098 if(sourceFileView->currentIndex().isValid())
2100 int iRow = sourceFileView->currentIndex().row();
2101 m_fileListModel->removeFile(sourceFileView->currentIndex());
2102 sourceFileView->selectRow(iRow < m_fileListModel->rowCount() ? iRow : m_fileListModel->rowCount()-1);
2107 * Clear files button
2109 void MainWindow::clearFilesButtonClicked(void)
2111 m_fileListModel->clearFiles();
2115 * Move file up button
2117 void MainWindow::fileUpButtonClicked(void)
2119 if(sourceFileView->currentIndex().isValid())
2121 int iRow = sourceFileView->currentIndex().row() - 1;
2122 m_fileListModel->moveFile(sourceFileView->currentIndex(), -1);
2123 sourceFileView->selectRow(iRow >= 0 ? iRow : 0);
2128 * Move file down button
2130 void MainWindow::fileDownButtonClicked(void)
2132 if(sourceFileView->currentIndex().isValid())
2134 int iRow = sourceFileView->currentIndex().row() + 1;
2135 m_fileListModel->moveFile(sourceFileView->currentIndex(), 1);
2136 sourceFileView->selectRow(iRow < m_fileListModel->rowCount() ? iRow : m_fileListModel->rowCount()-1);
2141 * Show details button
2143 void MainWindow::showDetailsButtonClicked(void)
2145 ABORT_IF_BUSY;
2147 int iResult = 0;
2148 MetaInfoDialog *metaInfoDialog = new MetaInfoDialog(this);
2149 QModelIndex index = sourceFileView->currentIndex();
2151 while(index.isValid())
2153 if(iResult > 0)
2155 index = m_fileListModel->index(index.row() + 1, index.column());
2156 sourceFileView->selectRow(index.row());
2158 if(iResult < 0)
2160 index = m_fileListModel->index(index.row() - 1, index.column());
2161 sourceFileView->selectRow(index.row());
2164 AudioFileModel &file = (*m_fileListModel)[index];
2165 TEMP_HIDE_DROPBOX
2167 iResult = metaInfoDialog->exec(file, index.row() > 0, index.row() < m_fileListModel->rowCount() - 1);
2170 if(iResult == INT_MAX)
2172 m_metaInfoModel->assignInfoFrom(file);
2173 tabWidget->setCurrentIndex(tabWidget->indexOf(tabMetaData));
2174 break;
2177 if(!iResult) break;
2180 LAMEXP_DELETE(metaInfoDialog);
2181 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
2182 sourceFilesScrollbarMoved(0);
2186 * Show context menu for source files
2188 void MainWindow::sourceFilesContextMenu(const QPoint &pos)
2190 QAbstractScrollArea *scrollArea = dynamic_cast<QAbstractScrollArea*>(QObject::sender());
2191 QWidget *sender = scrollArea ? scrollArea->viewport() : dynamic_cast<QWidget*>(QObject::sender());
2193 if(sender)
2195 if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0)
2197 m_sourceFilesContextMenu->popup(sender->mapToGlobal(pos));
2203 * Scrollbar of source files moved
2205 void MainWindow::sourceFilesScrollbarMoved(int)
2207 sourceFileView->resizeColumnToContents(0);
2211 * Open selected file in external player
2213 void MainWindow::previewContextActionTriggered(void)
2215 const static char *appNames[3] = {"smplayer_portable.exe", "smplayer.exe", "mplayer.exe"};
2216 const static wchar_t *registryKey = L"SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{DB9E4EAB-2717-499F-8D56-4CC8A644AB60}";
2218 QModelIndex index = sourceFileView->currentIndex();
2219 if(!index.isValid())
2221 return;
2224 QString mplayerPath;
2225 HKEY registryKeyHandle;
2227 if(RegOpenKeyExW(HKEY_LOCAL_MACHINE, registryKey, 0, KEY_READ, &registryKeyHandle) == ERROR_SUCCESS)
2229 wchar_t Buffer[4096];
2230 DWORD BuffSize = sizeof(wchar_t*) * 4096;
2231 if(RegQueryValueExW(registryKeyHandle, L"InstallLocation", 0, 0, reinterpret_cast<BYTE*>(Buffer), &BuffSize) == ERROR_SUCCESS)
2233 mplayerPath = QString::fromUtf16(reinterpret_cast<const unsigned short*>(Buffer));
2237 if(!mplayerPath.isEmpty())
2239 QDir mplayerDir(mplayerPath);
2240 if(mplayerDir.exists())
2242 for(int i = 0; i < 3; i++)
2244 if(mplayerDir.exists(appNames[i]))
2246 QProcess::startDetached(mplayerDir.absoluteFilePath(appNames[i]), QStringList() << QDir::toNativeSeparators(m_fileListModel->getFile(index).filePath()));
2247 return;
2253 QDesktopServices::openUrl(QString("file:///").append(m_fileListModel->getFile(index).filePath()));
2257 * Find selected file in explorer
2259 void MainWindow::findFileContextActionTriggered(void)
2261 QModelIndex index = sourceFileView->currentIndex();
2262 if(index.isValid())
2264 QString systemRootPath;
2266 QDir systemRoot(lamexp_known_folder(lamexp_folder_systemfolder));
2267 if(systemRoot.exists() && systemRoot.cdUp())
2269 systemRootPath = systemRoot.canonicalPath();
2272 if(!systemRootPath.isEmpty())
2274 QFileInfo explorer(QString("%1/explorer.exe").arg(systemRootPath));
2275 if(explorer.exists() && explorer.isFile())
2277 QProcess::execute(explorer.canonicalFilePath(), QStringList() << "/select," << QDir::toNativeSeparators(m_fileListModel->getFile(index).filePath()));
2278 return;
2281 else
2283 qWarning("SystemRoot directory could not be detected!");
2289 * Add all pending files
2291 void MainWindow::handleDelayedFiles(void)
2293 m_delayedFileTimer->stop();
2295 if(m_delayedFileList->isEmpty())
2297 return;
2300 if(m_banner->isVisible())
2302 m_delayedFileTimer->start(5000);
2303 return;
2306 QStringList selectedFiles;
2307 tabWidget->setCurrentIndex(0);
2309 while(!m_delayedFileList->isEmpty())
2311 QFileInfo currentFile = QFileInfo(m_delayedFileList->takeFirst());
2312 if(!currentFile.exists() || !currentFile.isFile())
2314 continue;
2316 selectedFiles << currentFile.canonicalFilePath();
2319 addFiles(selectedFiles);
2323 * Export Meta tags to CSV file
2325 void MainWindow::exportCsvContextActionTriggered(void)
2327 TEMP_HIDE_DROPBOX
2329 QString selectedCsvFile;
2331 if(USE_NATIVE_FILE_DIALOG)
2333 selectedCsvFile = QFileDialog::getSaveFileName(this, tr("Save CSV file"), m_settings->mostRecentInputPath(), QString("%1 (*.csv)").arg(tr("CSV File")));
2335 else
2337 QFileDialog dialog(this, tr("Save CSV file"));
2338 dialog.setFileMode(QFileDialog::AnyFile);
2339 dialog.setAcceptMode(QFileDialog::AcceptSave);
2340 dialog.setNameFilter(QString("%1 (*.csv)").arg(tr("CSV File")));
2341 dialog.setDirectory(m_settings->mostRecentInputPath());
2342 if(dialog.exec())
2344 selectedCsvFile = dialog.selectedFiles().first();
2348 if(!selectedCsvFile.isEmpty())
2350 m_settings->mostRecentInputPath(QFileInfo(selectedCsvFile).canonicalPath());
2351 switch(m_fileListModel->exportToCsv(selectedCsvFile))
2353 case FileListModel::CsvError_NoTags:
2354 QMessageBox::critical(this, tr("CSV Export"), NOBR(tr("Sorry, there are no meta tags that can be exported!")));
2355 break;
2356 case FileListModel::CsvError_FileOpen:
2357 QMessageBox::critical(this, tr("CSV Export"), NOBR(tr("Sorry, failed to open CSV file for writing!")));
2358 break;
2359 case FileListModel::CsvError_FileWrite:
2360 QMessageBox::critical(this, tr("CSV Export"), NOBR(tr("Sorry, failed to write to the CSV file!")));
2361 break;
2362 case FileListModel::CsvError_OK:
2363 QMessageBox::information(this, tr("CSV Export"), NOBR(tr("The CSV files was created successfully!")));
2364 break;
2365 default:
2366 qWarning("exportToCsv: Unknown return code!");
2374 * Import Meta tags from CSV file
2376 void MainWindow::importCsvContextActionTriggered(void)
2378 TEMP_HIDE_DROPBOX
2380 QString selectedCsvFile;
2382 if(USE_NATIVE_FILE_DIALOG)
2384 selectedCsvFile = QFileDialog::getOpenFileName(this, tr("Open CSV file"), m_settings->mostRecentInputPath(), QString("%1 (*.csv)").arg(tr("CSV File")));
2386 else
2388 QFileDialog dialog(this, tr("Open CSV file"));
2389 dialog.setFileMode(QFileDialog::ExistingFile);
2390 dialog.setNameFilter(QString("%1 (*.csv)").arg(tr("CSV File")));
2391 dialog.setDirectory(m_settings->mostRecentInputPath());
2392 if(dialog.exec())
2394 selectedCsvFile = dialog.selectedFiles().first();
2398 if(!selectedCsvFile.isEmpty())
2400 m_settings->mostRecentInputPath(QFileInfo(selectedCsvFile).canonicalPath());
2401 switch(m_fileListModel->importFromCsv(this, selectedCsvFile))
2403 case FileListModel::CsvError_FileOpen:
2404 QMessageBox::critical(this, tr("CSV Import"), NOBR(tr("Sorry, failed to open CSV file for reading!")));
2405 break;
2406 case FileListModel::CsvError_FileRead:
2407 QMessageBox::critical(this, tr("CSV Import"), NOBR(tr("Sorry, failed to read from the CSV file!")));
2408 break;
2409 case FileListModel::CsvError_NoTags:
2410 QMessageBox::critical(this, tr("CSV Import"), NOBR(tr("Sorry, the CSV file does not contain any known fields!")));
2411 break;
2412 case FileListModel::CsvError_Incomplete:
2413 QMessageBox::warning(this, tr("CSV Import"), NOBR(tr("CSV file is incomplete. Not all files were updated!")));
2414 break;
2415 case FileListModel::CsvError_OK:
2416 QMessageBox::information(this, tr("CSV Import"), NOBR(tr("The CSV files was imported successfully!")));
2417 break;
2418 case FileListModel::CsvError_Aborted:
2419 /* User aborted, ignore! */
2420 break;
2421 default:
2422 qWarning("exportToCsv: Unknown return code!");
2429 * Show or hide Drag'n'Drop notice after model reset
2431 void MainWindow::sourceModelChanged(void)
2433 m_dropNoteLabel->setVisible(m_fileListModel->rowCount() <= 0);
2436 // =========================================================
2437 // Output folder slots
2438 // =========================================================
2441 * Output folder changed (mouse clicked)
2443 void MainWindow::outputFolderViewClicked(const QModelIndex &index)
2445 if(index.isValid() && (outputFolderView->currentIndex() != index))
2447 outputFolderView->setCurrentIndex(index);
2450 if(m_fileSystemModel && index.isValid())
2452 QString selectedDir = m_fileSystemModel->filePath(index);
2453 if(selectedDir.length() < 3) selectedDir.append(QDir::separator());
2454 outputFolderLabel->setText(QDir::toNativeSeparators(selectedDir));
2455 m_settings->outputDir(selectedDir);
2457 else
2459 outputFolderLabel->setText(QDir::toNativeSeparators(m_settings->outputDir()));
2464 * Output folder changed (mouse moved)
2466 void MainWindow::outputFolderViewMoved(const QModelIndex &index)
2468 if(QApplication::mouseButtons() & Qt::LeftButton)
2470 outputFolderViewClicked(index);
2475 * Goto desktop button
2477 void MainWindow::gotoDesktopButtonClicked(void)
2479 if(!m_fileSystemModel)
2481 qWarning("File system model not initialized yet!");
2482 return;
2485 QString desktopPath = QDesktopServices::storageLocation(QDesktopServices::DesktopLocation);
2487 if(!desktopPath.isEmpty() && QDir(desktopPath).exists())
2489 outputFolderView->setCurrentIndex(m_fileSystemModel->index(desktopPath));
2490 outputFolderViewClicked(outputFolderView->currentIndex());
2491 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2493 else
2495 buttonGotoDesktop->setEnabled(false);
2500 * Goto home folder button
2502 void MainWindow::gotoHomeFolderButtonClicked(void)
2504 if(!m_fileSystemModel)
2506 qWarning("File system model not initialized yet!");
2507 return;
2510 QString homePath = QDesktopServices::storageLocation(QDesktopServices::HomeLocation);
2512 if(!homePath.isEmpty() && QDir(homePath).exists())
2514 outputFolderView->setCurrentIndex(m_fileSystemModel->index(homePath));
2515 outputFolderViewClicked(outputFolderView->currentIndex());
2516 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2518 else
2520 buttonGotoHome->setEnabled(false);
2525 * Goto music folder button
2527 void MainWindow::gotoMusicFolderButtonClicked(void)
2529 if(!m_fileSystemModel)
2531 qWarning("File system model not initialized yet!");
2532 return;
2535 QString musicPath = QDesktopServices::storageLocation(QDesktopServices::MusicLocation);
2537 if(!musicPath.isEmpty() && QDir(musicPath).exists())
2539 outputFolderView->setCurrentIndex(m_fileSystemModel->index(musicPath));
2540 outputFolderViewClicked(outputFolderView->currentIndex());
2541 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2543 else
2545 buttonGotoMusic->setEnabled(false);
2550 * Goto music favorite output folder
2552 void MainWindow::gotoFavoriteFolder(void)
2554 if(!m_fileSystemModel)
2556 qWarning("File system model not initialized yet!");
2557 return;
2560 QAction *item = dynamic_cast<QAction*>(QObject::sender());
2562 if(item)
2564 QDir path(item->data().toString());
2565 if(path.exists())
2567 outputFolderView->setCurrentIndex(m_fileSystemModel->index(path.canonicalPath()));
2568 outputFolderViewClicked(outputFolderView->currentIndex());
2569 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2571 else
2573 MessageBeep(MB_ICONERROR);
2574 m_outputFolderFavoritesMenu->removeAction(item);
2575 item->deleteLater();
2581 * Make folder button
2583 void MainWindow::makeFolderButtonClicked(void)
2585 ABORT_IF_BUSY;
2587 if(!m_fileSystemModel)
2589 qWarning("File system model not initialized yet!");
2590 return;
2593 QDir basePath(m_fileSystemModel->fileInfo(outputFolderView->currentIndex()).absoluteFilePath());
2594 QString suggestedName = tr("New Folder");
2596 if(!m_metaData->fileArtist().isEmpty() && !m_metaData->fileAlbum().isEmpty())
2598 suggestedName = QString("%1 - %2").arg(m_metaData->fileArtist(), m_metaData->fileAlbum());
2600 else if(!m_metaData->fileArtist().isEmpty())
2602 suggestedName = m_metaData->fileArtist();
2604 else if(!m_metaData->fileAlbum().isEmpty())
2606 suggestedName = m_metaData->fileAlbum();
2608 else
2610 for(int i = 0; i < m_fileListModel->rowCount(); i++)
2612 AudioFileModel audioFile = m_fileListModel->getFile(m_fileListModel->index(i, 0));
2613 if(!audioFile.fileAlbum().isEmpty() || !audioFile.fileArtist().isEmpty())
2615 if(!audioFile.fileArtist().isEmpty() && !audioFile.fileAlbum().isEmpty())
2617 suggestedName = QString("%1 - %2").arg(audioFile.fileArtist(), audioFile.fileAlbum());
2619 else if(!audioFile.fileArtist().isEmpty())
2621 suggestedName = audioFile.fileArtist();
2623 else if(!audioFile.fileAlbum().isEmpty())
2625 suggestedName = audioFile.fileAlbum();
2627 break;
2632 suggestedName = lamexp_clean_filename(suggestedName);
2634 while(true)
2636 bool bApplied = false;
2637 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();
2639 if(bApplied)
2641 folderName = lamexp_clean_filepath(folderName.simplified());
2643 if(folderName.isEmpty())
2645 MessageBeep(MB_ICONERROR);
2646 continue;
2649 int i = 1;
2650 QString newFolder = folderName;
2652 while(basePath.exists(newFolder))
2654 newFolder = QString(folderName).append(QString().sprintf(" (%d)", ++i));
2657 if(basePath.mkpath(newFolder))
2659 QDir createdDir = basePath;
2660 if(createdDir.cd(newFolder))
2662 QModelIndex newIndex = m_fileSystemModel->index(createdDir.canonicalPath());
2663 outputFolderView->setCurrentIndex(newIndex);
2664 outputFolderViewClicked(newIndex);
2665 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2668 else
2670 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!")));
2673 break;
2678 * Output to source dir changed
2680 void MainWindow::saveToSourceFolderChanged(void)
2682 m_settings->outputToSourceDir(saveToSourceFolderCheckBox->isChecked());
2686 * Prepend relative source file path to output file name changed
2688 void MainWindow::prependRelativePathChanged(void)
2690 m_settings->prependRelativeSourcePath(prependRelativePathCheckBox->isChecked());
2694 * Show context menu for output folder
2696 void MainWindow::outputFolderContextMenu(const QPoint &pos)
2698 QAbstractScrollArea *scrollArea = dynamic_cast<QAbstractScrollArea*>(QObject::sender());
2699 QWidget *sender = scrollArea ? scrollArea->viewport() : dynamic_cast<QWidget*>(QObject::sender());
2701 if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0)
2703 m_outputFolderContextMenu->popup(sender->mapToGlobal(pos));
2708 * Show selected folder in explorer
2710 void MainWindow::showFolderContextActionTriggered(void)
2712 if(!m_fileSystemModel)
2714 qWarning("File system model not initialized yet!");
2715 return;
2718 QString path = QDir::toNativeSeparators(m_fileSystemModel->filePath(outputFolderView->currentIndex()));
2719 if(!path.endsWith(QDir::separator())) path.append(QDir::separator());
2720 ShellExecuteW(reinterpret_cast<HWND>(this->winId()), L"explore", QWCHAR(path), NULL, NULL, SW_SHOW);
2724 * Refresh the directory outline
2726 void MainWindow::refreshFolderContextActionTriggered(void)
2728 //force re-initialization
2729 QTimer::singleShot(0, this, SLOT(initOutputFolderModel()));
2733 * Add current folder to favorites
2735 void MainWindow::addFavoriteFolderActionTriggered(void)
2737 QString path = m_fileSystemModel->filePath(outputFolderView->currentIndex());
2738 QStringList favorites = m_settings->favoriteOutputFolders().split("|", QString::SkipEmptyParts);
2740 if(!favorites.contains(path, Qt::CaseInsensitive))
2742 favorites.append(path);
2743 while(favorites.count() > 6) favorites.removeFirst();
2745 else
2747 MessageBeep(MB_ICONWARNING);
2750 m_settings->favoriteOutputFolders(favorites.join("|"));
2751 refreshFavorites();
2755 * Output folder edit finished
2757 void MainWindow::outputFolderEditFinished(void)
2759 if(outputFolderEdit->isHidden())
2761 return; //Not currently in edit mode!
2764 bool ok = false;
2766 QString text = QDir::fromNativeSeparators(outputFolderEdit->text().trimmed());
2767 while(text.startsWith('"') || text.startsWith('/')) text = text.right(text.length() - 1).trimmed();
2768 while(text.endsWith('"') || text.endsWith('/')) text = text.left(text.length() - 1).trimmed();
2770 static const char *str = "?*<>|\"";
2771 for(size_t i = 0; str[i]; i++) text.replace(str[i], "_");
2773 if(!((text.length() >= 2) && text.at(0).isLetter() && text.at(1) == QChar(':')))
2775 text = QString("%1/%2").arg(QDir::fromNativeSeparators(outputFolderLabel->text()), text);
2778 if(text.length() == 2) text += "/"; /* "X:" => "X:/" */
2780 while(text.length() > 2)
2782 QFileInfo info(text);
2783 if(info.exists() && info.isDir())
2785 QModelIndex index = m_fileSystemModel->index(QFileInfo(info.canonicalFilePath()).absoluteFilePath());
2786 if(index.isValid())
2788 ok = true;
2789 outputFolderView->setCurrentIndex(index);
2790 outputFolderViewClicked(index);
2791 break;
2794 else if(info.exists() && info.isFile())
2796 QModelIndex index = m_fileSystemModel->index(QFileInfo(info.canonicalPath()).absoluteFilePath());
2797 if(index.isValid())
2799 ok = true;
2800 outputFolderView->setCurrentIndex(index);
2801 outputFolderViewClicked(index);
2802 break;
2806 text = text.left(text.length() - 1).trimmed();
2809 outputFolderEdit->setVisible(false);
2810 outputFolderLabel->setVisible(true);
2811 outputFolderView->setEnabled(true);
2813 if(!ok) MessageBeep(MB_ICONERROR);
2814 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2818 * Initialize file system model
2820 void MainWindow::initOutputFolderModel(void)
2822 if(m_outputFolderNoteBox->isHidden())
2824 m_outputFolderNoteBox->show();
2825 m_outputFolderNoteBox->repaint();
2826 m_outputFolderViewInitCounter = 4;
2828 if(m_fileSystemModel)
2830 SET_MODEL(outputFolderView, NULL);
2831 LAMEXP_DELETE(m_fileSystemModel);
2832 outputFolderView->repaint();
2835 if(m_fileSystemModel = new QFileSystemModelEx())
2837 m_fileSystemModel->installEventFilter(this);
2838 connect(m_fileSystemModel, SIGNAL(directoryLoaded(QString)), this, SLOT(outputFolderDirectoryLoaded(QString)));
2839 connect(m_fileSystemModel, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(outputFolderRowsInserted(QModelIndex,int,int)));
2841 SET_MODEL(outputFolderView, m_fileSystemModel);
2842 outputFolderView->header()->setStretchLastSection(true);
2843 outputFolderView->header()->hideSection(1);
2844 outputFolderView->header()->hideSection(2);
2845 outputFolderView->header()->hideSection(3);
2847 m_fileSystemModel->setRootPath("");
2848 QModelIndex index = m_fileSystemModel->index(m_settings->outputDir());
2849 if(index.isValid()) outputFolderView->setCurrentIndex(index);
2850 outputFolderViewClicked(outputFolderView->currentIndex());
2853 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2854 QTimer::singleShot(125, this, SLOT(initOutputFolderModel_doAsync()));
2859 * Initialize file system model (do NOT call this one directly!)
2861 void MainWindow::initOutputFolderModel_doAsync(void)
2863 if(m_outputFolderViewInitCounter > 0)
2865 m_outputFolderViewInitCounter--;
2866 QTimer::singleShot(125, this, SLOT(initOutputFolderModel_doAsync()));
2868 else
2870 QTimer::singleShot(125, m_outputFolderNoteBox, SLOT(hide()));
2871 outputFolderView->setFocus();
2876 * Center current folder in view
2878 void MainWindow::centerOutputFolderModel(void)
2880 if(outputFolderView->isVisible())
2882 centerOutputFolderModel_doAsync();
2883 QTimer::singleShot(125, this, SLOT(centerOutputFolderModel_doAsync()));
2888 * Center current folder in view (do NOT call this one directly!)
2890 void MainWindow::centerOutputFolderModel_doAsync(void)
2892 if(outputFolderView->isVisible())
2894 m_outputFolderViewCentering = true;
2895 const QModelIndex index = outputFolderView->currentIndex();
2896 outputFolderView->scrollTo(index, QAbstractItemView::PositionAtCenter);
2897 outputFolderView->setFocus();
2902 * File system model asynchronously loaded a dir
2904 void MainWindow::outputFolderDirectoryLoaded(const QString &path)
2906 if(m_outputFolderViewCentering)
2908 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2913 * File system model inserted new items
2915 void MainWindow::outputFolderRowsInserted(const QModelIndex &parent, int start, int end)
2917 if(m_outputFolderViewCentering)
2919 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2924 * Directory view item was expanded by user
2926 void MainWindow::outputFolderItemExpanded(const QModelIndex &item)
2928 //We need to stop centering as soon as the user has expanded an item manually!
2929 m_outputFolderViewCentering = false;
2932 // =========================================================
2933 // Metadata tab slots
2934 // =========================================================
2937 * Edit meta button clicked
2939 void MainWindow::editMetaButtonClicked(void)
2941 ABORT_IF_BUSY;
2943 const QModelIndex index = metaDataView->currentIndex();
2945 if(index.isValid())
2947 m_metaInfoModel->editItem(index, this);
2949 if(index.row() == 4)
2951 m_settings->metaInfoPosition(m_metaData->filePosition());
2957 * Reset meta button clicked
2959 void MainWindow::clearMetaButtonClicked(void)
2961 ABORT_IF_BUSY;
2962 m_metaInfoModel->clearData();
2966 * Meta tags enabled changed
2968 void MainWindow::metaTagsEnabledChanged(void)
2970 m_settings->writeMetaTags(writeMetaDataCheckBox->isChecked());
2974 * Playlist enabled changed
2976 void MainWindow::playlistEnabledChanged(void)
2978 m_settings->createPlaylist(generatePlaylistCheckBox->isChecked());
2981 // =========================================================
2982 // Compression tab slots
2983 // =========================================================
2986 * Update encoder
2988 void MainWindow::updateEncoder(int id)
2990 m_settings->compressionEncoder(id);
2992 switch(m_settings->compressionEncoder())
2994 case SettingsModel::VorbisEncoder:
2995 radioButtonModeQuality->setEnabled(true);
2996 radioButtonModeAverageBitrate->setEnabled(true);
2997 radioButtonConstBitrate->setEnabled(false);
2998 if(radioButtonConstBitrate->isChecked()) radioButtonModeQuality->setChecked(true);
2999 sliderBitrate->setEnabled(true);
3000 break;
3001 case SettingsModel::AC3Encoder:
3002 radioButtonModeQuality->setEnabled(true);
3003 radioButtonModeQuality->setChecked(true);
3004 radioButtonModeAverageBitrate->setEnabled(false);
3005 radioButtonConstBitrate->setEnabled(true);
3006 sliderBitrate->setEnabled(true);
3007 break;
3008 case SettingsModel::FLACEncoder:
3009 radioButtonModeQuality->setEnabled(false);
3010 radioButtonModeQuality->setChecked(true);
3011 radioButtonModeAverageBitrate->setEnabled(false);
3012 radioButtonConstBitrate->setEnabled(false);
3013 sliderBitrate->setEnabled(true);
3014 break;
3015 case SettingsModel::PCMEncoder:
3016 radioButtonModeQuality->setEnabled(false);
3017 radioButtonModeQuality->setChecked(true);
3018 radioButtonModeAverageBitrate->setEnabled(false);
3019 radioButtonConstBitrate->setEnabled(false);
3020 sliderBitrate->setEnabled(false);
3021 break;
3022 case SettingsModel::AACEncoder:
3023 radioButtonModeQuality->setEnabled(true);
3024 radioButtonModeAverageBitrate->setEnabled(!m_fhgEncoderAvailable);
3025 if(m_fhgEncoderAvailable && radioButtonModeAverageBitrate->isChecked()) radioButtonConstBitrate->setChecked(true);
3026 radioButtonConstBitrate->setEnabled(true);
3027 sliderBitrate->setEnabled(true);
3028 break;
3029 case SettingsModel::DCAEncoder:
3030 radioButtonModeQuality->setEnabled(false);
3031 radioButtonModeAverageBitrate->setEnabled(false);
3032 radioButtonConstBitrate->setEnabled(true);
3033 radioButtonConstBitrate->setChecked(true);
3034 sliderBitrate->setEnabled(true);
3035 break;
3036 default:
3037 radioButtonModeQuality->setEnabled(true);
3038 radioButtonModeAverageBitrate->setEnabled(true);
3039 radioButtonConstBitrate->setEnabled(true);
3040 sliderBitrate->setEnabled(true);
3041 break;
3044 if(m_settings->compressionEncoder() == SettingsModel::AACEncoder)
3046 const QString encoderName = m_qaacEncoderAvailable ? tr("QAAC (Apple)") : (m_fhgEncoderAvailable ? tr("FHG AAC (Winamp)") : (m_neroEncoderAvailable ? tr("Nero AAC") : tr("Not available!")));
3047 labelEncoderInfo->setVisible(true);
3048 labelEncoderInfo->setText(tr("Current AAC Encoder: %1").arg(encoderName));
3050 else
3052 labelEncoderInfo->setVisible(false);
3055 updateRCMode(m_modeButtonGroup->checkedId());
3059 * Update rate-control mode
3061 void MainWindow::updateRCMode(int id)
3063 m_settings->compressionRCMode(id);
3065 switch(m_settings->compressionEncoder())
3067 case SettingsModel::MP3Encoder:
3068 switch(m_settings->compressionRCMode())
3070 case SettingsModel::VBRMode:
3071 sliderBitrate->setMinimum(0);
3072 sliderBitrate->setMaximum(9);
3073 break;
3074 default:
3075 sliderBitrate->setMinimum(0);
3076 sliderBitrate->setMaximum(13);
3077 break;
3079 break;
3080 case SettingsModel::VorbisEncoder:
3081 switch(m_settings->compressionRCMode())
3083 case SettingsModel::VBRMode:
3084 sliderBitrate->setMinimum(-2);
3085 sliderBitrate->setMaximum(10);
3086 break;
3087 default:
3088 sliderBitrate->setMinimum(4);
3089 sliderBitrate->setMaximum(63);
3090 break;
3092 break;
3093 case SettingsModel::AC3Encoder:
3094 switch(m_settings->compressionRCMode())
3096 case SettingsModel::VBRMode:
3097 sliderBitrate->setMinimum(0);
3098 sliderBitrate->setMaximum(16);
3099 break;
3100 default:
3101 sliderBitrate->setMinimum(0);
3102 sliderBitrate->setMaximum(18);
3103 break;
3105 break;
3106 case SettingsModel::AACEncoder:
3107 switch(m_settings->compressionRCMode())
3109 case SettingsModel::VBRMode:
3110 sliderBitrate->setMinimum(0);
3111 sliderBitrate->setMaximum(20);
3112 break;
3113 default:
3114 sliderBitrate->setMinimum(4);
3115 sliderBitrate->setMaximum(63);
3116 break;
3118 break;
3119 case SettingsModel::FLACEncoder:
3120 sliderBitrate->setMinimum(0);
3121 sliderBitrate->setMaximum(8);
3122 break;
3123 case SettingsModel::DCAEncoder:
3124 sliderBitrate->setMinimum(1);
3125 sliderBitrate->setMaximum(128);
3126 break;
3127 case SettingsModel::PCMEncoder:
3128 sliderBitrate->setMinimum(0);
3129 sliderBitrate->setMaximum(2);
3130 sliderBitrate->setValue(1);
3131 break;
3132 default:
3133 sliderBitrate->setMinimum(0);
3134 sliderBitrate->setMaximum(0);
3135 break;
3138 updateBitrate(sliderBitrate->value());
3142 * Update bitrate
3144 void MainWindow::updateBitrate(int value)
3146 m_settings->compressionBitrate(value);
3148 switch(m_settings->compressionRCMode())
3150 case SettingsModel::VBRMode:
3151 switch(m_settings->compressionEncoder())
3153 case SettingsModel::MP3Encoder:
3154 labelBitrate->setText(tr("Quality Level %1").arg(9 - value));
3155 break;
3156 case SettingsModel::VorbisEncoder:
3157 labelBitrate->setText(tr("Quality Level %1").arg(value));
3158 break;
3159 case SettingsModel::AACEncoder:
3160 labelBitrate->setText(tr("Quality Level %1").arg(QString().sprintf("%.2f", static_cast<double>(value * 5) / 100.0)));
3161 break;
3162 case SettingsModel::FLACEncoder:
3163 labelBitrate->setText(tr("Compression %1").arg(value));
3164 break;
3165 case SettingsModel::AC3Encoder:
3166 labelBitrate->setText(tr("Quality Level %1").arg(qMin(1024, qMax(0, value * 64))));
3167 break;
3168 case SettingsModel::PCMEncoder:
3169 labelBitrate->setText(tr("Uncompressed"));
3170 break;
3171 default:
3172 labelBitrate->setText(QString::number(value));
3173 break;
3175 break;
3176 case SettingsModel::ABRMode:
3177 switch(m_settings->compressionEncoder())
3179 case SettingsModel::MP3Encoder:
3180 labelBitrate->setText(QString("&asymp; %1 kbps").arg(SettingsModel::mp3Bitrates[value]));
3181 break;
3182 case SettingsModel::FLACEncoder:
3183 labelBitrate->setText(tr("Compression %1").arg(value));
3184 break;
3185 case SettingsModel::AC3Encoder:
3186 labelBitrate->setText(QString("&asymp; %1 kbps").arg(SettingsModel::ac3Bitrates[value]));
3187 break;
3188 case SettingsModel::PCMEncoder:
3189 labelBitrate->setText(tr("Uncompressed"));
3190 break;
3191 default:
3192 labelBitrate->setText(QString("&asymp; %1 kbps").arg(qMin(500, value * 8)));
3193 break;
3195 break;
3196 default:
3197 switch(m_settings->compressionEncoder())
3199 case SettingsModel::MP3Encoder:
3200 labelBitrate->setText(QString("%1 kbps").arg(SettingsModel::mp3Bitrates[value]));
3201 break;
3202 case SettingsModel::FLACEncoder:
3203 labelBitrate->setText(tr("Compression %1").arg(value));
3204 break;
3205 case SettingsModel::AC3Encoder:
3206 labelBitrate->setText(QString("%1 kbps").arg(SettingsModel::ac3Bitrates[value]));
3207 break;
3208 case SettingsModel::DCAEncoder:
3209 labelBitrate->setText(QString("%1 kbps").arg(value * 32));
3210 break;
3211 case SettingsModel::PCMEncoder:
3212 labelBitrate->setText(tr("Uncompressed"));
3213 break;
3214 default:
3215 labelBitrate->setText(QString("%1 kbps").arg(qMin(500, value * 8)));
3216 break;
3218 break;
3222 // =========================================================
3223 // Advanced option slots
3224 // =========================================================
3227 * Lame algorithm quality changed
3229 void MainWindow::updateLameAlgoQuality(int value)
3231 QString text;
3233 switch(value)
3235 case 4:
3236 text = tr("Best Quality (Very Slow)");
3237 break;
3238 case 3:
3239 text = tr("High Quality (Recommended)");
3240 break;
3241 case 2:
3242 text = tr("Average Quality (Default)");
3243 break;
3244 case 1:
3245 text = tr("Low Quality (Fast)");
3246 break;
3247 case 0:
3248 text = tr("Poor Quality (Very Fast)");
3249 break;
3252 if(!text.isEmpty())
3254 m_settings->lameAlgoQuality(value);
3255 labelLameAlgoQuality->setText(text);
3258 bool warning = (value == 0), notice = (value == 4);
3259 labelLameAlgoQualityWarning->setVisible(warning);
3260 labelLameAlgoQualityWarningIcon->setVisible(warning);
3261 labelLameAlgoQualityNotice->setVisible(notice);
3262 labelLameAlgoQualityNoticeIcon->setVisible(notice);
3263 labelLameAlgoQualitySpacer->setVisible(warning || notice);
3267 * Bitrate management endabled/disabled
3269 void MainWindow::bitrateManagementEnabledChanged(bool checked)
3271 m_settings->bitrateManagementEnabled(checked);
3275 * Minimum bitrate has changed
3277 void MainWindow::bitrateManagementMinChanged(int value)
3279 if(value > spinBoxBitrateManagementMax->value())
3281 spinBoxBitrateManagementMin->setValue(spinBoxBitrateManagementMax->value());
3282 m_settings->bitrateManagementMinRate(spinBoxBitrateManagementMax->value());
3284 else
3286 m_settings->bitrateManagementMinRate(value);
3291 * Maximum bitrate has changed
3293 void MainWindow::bitrateManagementMaxChanged(int value)
3295 if(value < spinBoxBitrateManagementMin->value())
3297 spinBoxBitrateManagementMax->setValue(spinBoxBitrateManagementMin->value());
3298 m_settings->bitrateManagementMaxRate(spinBoxBitrateManagementMin->value());
3300 else
3302 m_settings->bitrateManagementMaxRate(value);
3307 * Channel mode has changed
3309 void MainWindow::channelModeChanged(int value)
3311 if(value >= 0) m_settings->lameChannelMode(value);
3315 * Sampling rate has changed
3317 void MainWindow::samplingRateChanged(int value)
3319 if(value >= 0) m_settings->samplingRate(value);
3323 * Nero AAC 2-Pass mode changed
3325 void MainWindow::neroAAC2PassChanged(bool checked)
3327 m_settings->neroAACEnable2Pass(checked);
3331 * Nero AAC profile mode changed
3333 void MainWindow::neroAACProfileChanged(int value)
3335 if(value >= 0) m_settings->aacEncProfile(value);
3339 * Aften audio coding mode changed
3341 void MainWindow::aftenCodingModeChanged(int value)
3343 if(value >= 0) m_settings->aftenAudioCodingMode(value);
3347 * Aften DRC mode changed
3349 void MainWindow::aftenDRCModeChanged(int value)
3351 if(value >= 0) m_settings->aftenDynamicRangeCompression(value);
3355 * Aften exponent search size changed
3357 void MainWindow::aftenSearchSizeChanged(int value)
3359 if(value >= 0) m_settings->aftenExponentSearchSize(value);
3363 * Aften fast bit allocation changed
3365 void MainWindow::aftenFastAllocationChanged(bool checked)
3367 m_settings->aftenFastBitAllocation(checked);
3371 * Normalization filter enabled changed
3373 void MainWindow::normalizationEnabledChanged(bool checked)
3375 m_settings->normalizationFilterEnabled(checked);
3379 * Normalization max. volume changed
3381 void MainWindow::normalizationMaxVolumeChanged(double value)
3383 m_settings->normalizationFilterMaxVolume(static_cast<int>(value * 100.0));
3387 * Normalization equalization mode changed
3389 void MainWindow::normalizationModeChanged(int mode)
3391 m_settings->normalizationFilterEqualizationMode(mode);
3395 * Tone adjustment has changed (Bass)
3397 void MainWindow::toneAdjustBassChanged(double value)
3399 m_settings->toneAdjustBass(static_cast<int>(value * 100.0));
3400 spinBoxToneAdjustBass->setPrefix((value > 0) ? "+" : QString());
3404 * Tone adjustment has changed (Treble)
3406 void MainWindow::toneAdjustTrebleChanged(double value)
3408 m_settings->toneAdjustTreble(static_cast<int>(value * 100.0));
3409 spinBoxToneAdjustTreble->setPrefix((value > 0) ? "+" : QString());
3413 * Tone adjustment has been reset
3415 void MainWindow::toneAdjustTrebleReset(void)
3417 spinBoxToneAdjustBass->setValue(m_settings->toneAdjustBassDefault());
3418 spinBoxToneAdjustTreble->setValue(m_settings->toneAdjustTrebleDefault());
3419 toneAdjustBassChanged(spinBoxToneAdjustBass->value());
3420 toneAdjustTrebleChanged(spinBoxToneAdjustTreble->value());
3424 * Custom encoder parameters changed
3426 void MainWindow::customParamsChanged(void)
3428 lineEditCustomParamLAME->setText(lineEditCustomParamLAME->text().simplified());
3429 lineEditCustomParamOggEnc->setText(lineEditCustomParamOggEnc->text().simplified());
3430 lineEditCustomParamNeroAAC->setText(lineEditCustomParamNeroAAC->text().simplified());
3431 lineEditCustomParamFLAC->setText(lineEditCustomParamFLAC->text().simplified());
3432 lineEditCustomParamAften->setText(lineEditCustomParamAften->text().simplified());
3434 bool customParamsUsed = false;
3435 if(!lineEditCustomParamLAME->text().isEmpty()) customParamsUsed = true;
3436 if(!lineEditCustomParamOggEnc->text().isEmpty()) customParamsUsed = true;
3437 if(!lineEditCustomParamNeroAAC->text().isEmpty()) customParamsUsed = true;
3438 if(!lineEditCustomParamFLAC->text().isEmpty()) customParamsUsed = true;
3439 if(!lineEditCustomParamAften->text().isEmpty()) customParamsUsed = true;
3441 labelCustomParamsIcon->setVisible(customParamsUsed);
3442 labelCustomParamsText->setVisible(customParamsUsed);
3443 labelCustomParamsSpacer->setVisible(customParamsUsed);
3445 m_settings->customParametersLAME(lineEditCustomParamLAME->text());
3446 m_settings->customParametersOggEnc(lineEditCustomParamOggEnc->text());
3447 m_settings->customParametersAacEnc(lineEditCustomParamNeroAAC->text());
3448 m_settings->customParametersFLAC(lineEditCustomParamFLAC->text());
3449 m_settings->customParametersAften(lineEditCustomParamAften->text());
3454 * Rename output files enabled changed
3456 void MainWindow::renameOutputEnabledChanged(bool checked)
3458 m_settings->renameOutputFilesEnabled(checked);
3462 * Rename output files patterm changed
3464 void MainWindow::renameOutputPatternChanged(void)
3466 QString temp = lineEditRenamePattern->text().simplified();
3467 lineEditRenamePattern->setText(temp.isEmpty() ? m_settings->renameOutputFilesPatternDefault() : temp);
3468 m_settings->renameOutputFilesPattern(lineEditRenamePattern->text());
3472 * Rename output files patterm changed
3474 void MainWindow::renameOutputPatternChanged(const QString &text)
3476 QString pattern(text.simplified());
3478 pattern.replace("<BaseName>", "The_White_Stripes_-_Fell_In_Love_With_A_Girl", Qt::CaseInsensitive);
3479 pattern.replace("<TrackNo>", "04", Qt::CaseInsensitive);
3480 pattern.replace("<Title>", "Fell In Love With A Girl", Qt::CaseInsensitive);
3481 pattern.replace("<Artist>", "The White Stripes", Qt::CaseInsensitive);
3482 pattern.replace("<Album>", "White Blood Cells", Qt::CaseInsensitive);
3483 pattern.replace("<Year>", "2001", Qt::CaseInsensitive);
3484 pattern.replace("<Comment>", "Encoded by LameXP", Qt::CaseInsensitive);
3486 if(pattern.compare(lamexp_clean_filename(pattern)))
3488 if(lineEditRenamePattern->palette().color(QPalette::Text) != Qt::red)
3490 MessageBeep(MB_ICONERROR);
3491 SET_TEXT_COLOR(lineEditRenamePattern, Qt::red);
3494 else
3496 if(lineEditRenamePattern->palette().color(QPalette::Text) != Qt::black)
3498 MessageBeep(MB_ICONINFORMATION);
3499 SET_TEXT_COLOR(lineEditRenamePattern, Qt::black);
3503 labelRanameExample->setText(lamexp_clean_filename(pattern));
3507 * Show list of rename macros
3509 void MainWindow::showRenameMacros(const QString &text)
3511 if(text.compare("reset", Qt::CaseInsensitive) == 0)
3513 lineEditRenamePattern->setText(m_settings->renameOutputFilesPatternDefault());
3514 return;
3517 const QString format = QString("<tr><td><tt>&lt;%1&gt;</tt></td><td>&nbsp;&nbsp;</td><td>%2</td></tr>");
3519 QString message = QString("<table>");
3520 message += QString(format).arg("BaseName", tr("File name without extension"));
3521 message += QString(format).arg("TrackNo", tr("Track number with leading zero"));
3522 message += QString(format).arg("Title", tr("Track title"));
3523 message += QString(format).arg("Artist", tr("Artist name"));
3524 message += QString(format).arg("Album", tr("Album name"));
3525 message += QString(format).arg("Year", tr("Year with (at least) four digits"));
3526 message += QString(format).arg("Comment", tr("Comment"));
3527 message += "</table><br><br>";
3528 message += QString("%1<br>").arg(tr("Characters forbidden in file names:"));
3529 message += "<b><tt>\\ / : * ? &lt; &gt; |<br>";
3531 QMessageBox::information(this, tr("Rename Macros"), message, tr("Discard"));
3534 void MainWindow::forceStereoDownmixEnabledChanged(bool checked)
3536 m_settings->forceStereoDownmix(checked);
3540 * Maximum number of instances changed
3542 void MainWindow::updateMaximumInstances(int value)
3544 labelMaxInstances->setText(tr("%1 Instance(s)").arg(QString::number(value)));
3545 m_settings->maximumInstances(checkBoxAutoDetectInstances->isChecked() ? NULL : value);
3549 * Auto-detect number of instances
3551 void MainWindow::autoDetectInstancesChanged(bool checked)
3553 m_settings->maximumInstances(checked ? NULL : sliderMaxInstances->value());
3557 * Browse for custom TEMP folder button clicked
3559 void MainWindow::browseCustomTempFolderButtonClicked(void)
3561 QString newTempFolder;
3563 if(USE_NATIVE_FILE_DIALOG)
3565 newTempFolder = QFileDialog::getExistingDirectory(this, QString(), m_settings->customTempPath());
3567 else
3569 QFileDialog dialog(this);
3570 dialog.setFileMode(QFileDialog::DirectoryOnly);
3571 dialog.setDirectory(m_settings->customTempPath());
3572 if(dialog.exec())
3574 newTempFolder = dialog.selectedFiles().first();
3578 if(!newTempFolder.isEmpty())
3580 QFile writeTest(QString("%1/~%2.tmp").arg(newTempFolder, lamexp_rand_str()));
3581 if(writeTest.open(QIODevice::ReadWrite))
3583 writeTest.remove();
3584 lineEditCustomTempFolder->setText(QDir::toNativeSeparators(newTempFolder));
3586 else
3588 QMessageBox::warning(this, tr("Access Denied"), tr("Cannot write to the selected directory. Please choose another directory!"));
3594 * Custom TEMP folder changed
3596 void MainWindow::customTempFolderChanged(const QString &text)
3598 m_settings->customTempPath(QDir::fromNativeSeparators(text));
3602 * Use custom TEMP folder option changed
3604 void MainWindow::useCustomTempFolderChanged(bool checked)
3606 m_settings->customTempPathEnabled(!checked);
3610 * Reset all advanced options to their defaults
3612 void MainWindow::resetAdvancedOptionsButtonClicked(void)
3614 sliderLameAlgoQuality->setValue(m_settings->lameAlgoQualityDefault());
3615 spinBoxBitrateManagementMin->setValue(m_settings->bitrateManagementMinRateDefault());
3616 spinBoxBitrateManagementMax->setValue(m_settings->bitrateManagementMaxRateDefault());
3617 spinBoxNormalizationFilter->setValue(static_cast<double>(m_settings->normalizationFilterMaxVolumeDefault()) / 100.0);
3618 spinBoxToneAdjustBass->setValue(static_cast<double>(m_settings->toneAdjustBassDefault()) / 100.0);
3619 spinBoxToneAdjustTreble->setValue(static_cast<double>(m_settings->toneAdjustTrebleDefault()) / 100.0);
3620 spinBoxAftenSearchSize->setValue(m_settings->aftenExponentSearchSizeDefault());
3621 comboBoxMP3ChannelMode->setCurrentIndex(m_settings->lameChannelModeDefault());
3622 comboBoxSamplingRate->setCurrentIndex(m_settings->samplingRateDefault());
3623 comboBoxAACProfile->setCurrentIndex(m_settings->aacEncProfileDefault());
3624 comboBoxAftenCodingMode->setCurrentIndex(m_settings->aftenAudioCodingModeDefault());
3625 comboBoxAftenDRCMode->setCurrentIndex(m_settings->aftenDynamicRangeCompressionDefault());
3626 comboBoxNormalizationMode->setCurrentIndex(m_settings->normalizationFilterEqualizationModeDefault());
3627 while(checkBoxBitrateManagement->isChecked() != m_settings->bitrateManagementEnabledDefault()) checkBoxBitrateManagement->click();
3628 while(checkBoxNeroAAC2PassMode->isChecked() != m_settings->neroAACEnable2PassDefault()) checkBoxNeroAAC2PassMode->click();
3629 while(checkBoxNormalizationFilter->isChecked() != m_settings->normalizationFilterEnabledDefault()) checkBoxNormalizationFilter->click();
3630 while(checkBoxAutoDetectInstances->isChecked() != (m_settings->maximumInstancesDefault() < 1)) checkBoxAutoDetectInstances->click();
3631 while(checkBoxUseSystemTempFolder->isChecked() == m_settings->customTempPathEnabledDefault()) checkBoxUseSystemTempFolder->click();
3632 while(checkBoxAftenFastAllocation->isChecked() != m_settings->aftenFastBitAllocationDefault()) checkBoxAftenFastAllocation->click();
3633 while(checkBoxRenameOutput->isChecked() != m_settings->renameOutputFilesEnabledDefault()) checkBoxRenameOutput->click();
3634 while(checkBoxForceStereoDownmix->isChecked() != m_settings->forceStereoDownmixDefault()) checkBoxForceStereoDownmix->click();
3635 lineEditCustomParamLAME->setText(m_settings->customParametersLAMEDefault());
3636 lineEditCustomParamOggEnc->setText(m_settings->customParametersOggEncDefault());
3637 lineEditCustomParamNeroAAC->setText(m_settings->customParametersAacEncDefault());
3638 lineEditCustomParamFLAC->setText(m_settings->customParametersFLACDefault());
3639 lineEditCustomTempFolder->setText(QDir::toNativeSeparators(m_settings->customTempPathDefault()));
3640 lineEditRenamePattern->setText(m_settings->renameOutputFilesPatternDefault());
3641 customParamsChanged();
3642 scrollArea->verticalScrollBar()->setValue(0);
3645 // =========================================================
3646 // Multi-instance handling slots
3647 // =========================================================
3650 * Other instance detected
3652 void MainWindow::notifyOtherInstance(void)
3654 if(!m_banner->isVisible())
3656 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);
3657 msgBox.exec();
3662 * Add file from another instance
3664 void MainWindow::addFileDelayed(const QString &filePath, bool tryASAP)
3666 if(tryASAP && !m_delayedFileTimer->isActive())
3668 qDebug("Received file: %s", filePath.toUtf8().constData());
3669 m_delayedFileList->append(filePath);
3670 QTimer::singleShot(0, this, SLOT(handleDelayedFiles()));
3673 m_delayedFileTimer->stop();
3674 qDebug("Received file: %s", filePath.toUtf8().constData());
3675 m_delayedFileList->append(filePath);
3676 m_delayedFileTimer->start(5000);
3680 * Add files from another instance
3682 void MainWindow::addFilesDelayed(const QStringList &filePaths, bool tryASAP)
3684 if(tryASAP && !m_delayedFileTimer->isActive())
3686 qDebug("Received %d file(s).", filePaths.count());
3687 m_delayedFileList->append(filePaths);
3688 QTimer::singleShot(0, this, SLOT(handleDelayedFiles()));
3690 else
3692 m_delayedFileTimer->stop();
3693 qDebug("Received %d file(s).", filePaths.count());
3694 m_delayedFileList->append(filePaths);
3695 m_delayedFileTimer->start(5000);
3700 * Add folder from another instance
3702 void MainWindow::addFolderDelayed(const QString &folderPath, bool recursive)
3704 if(!m_banner->isVisible())
3706 addFolder(folderPath, recursive, true);
3710 // =========================================================
3711 // Misc slots
3712 // =========================================================
3715 * Restore the override cursor
3717 void MainWindow::restoreCursor(void)
3719 QApplication::restoreOverrideCursor();