OSDN Git Service

Switched the method of how the Designer UI file is used in the MainWindow class to...
[lamexp/LameXP.git] / src / Dialog_MainWindow.cpp
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.
14 //
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.
18 //
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
21
22 #include "Dialog_MainWindow.h"
23
24 //UIC includes
25 #include "../tmp/UIC_MainWindow.h"
26
27 //LameXP includes
28 #include "Global.h"
29 #include "Resource.h"
30 #include "Dialog_WorkingBanner.h"
31 #include "Dialog_MetaInfo.h"
32 #include "Dialog_About.h"
33 #include "Dialog_Update.h"
34 #include "Dialog_DropBox.h"
35 #include "Dialog_CueImport.h"
36 #include "Dialog_LogView.h"
37 #include "Thread_FileAnalyzer.h"
38 #include "Thread_FileAnalyzer_ST.h"
39 #include "Thread_MessageHandler.h"
40 #include "Model_MetaInfo.h"
41 #include "Model_Settings.h"
42 #include "Model_FileList.h"
43 #include "Model_FileSystem.h"
44 #include "WinSevenTaskbar.h"
45 #include "Registry_Decoder.h"
46 #include "ShellIntegration.h"
47 #include "CustomEventFilter.h"
48
49 //Qt includes
50 #include <QMessageBox>
51 #include <QTimer>
52 #include <QDesktopWidget>
53 #include <QDate>
54 #include <QFileDialog>
55 #include <QInputDialog>
56 #include <QFileSystemModel>
57 #include <QDesktopServices>
58 #include <QUrl>
59 #include <QPlastiqueStyle>
60 #include <QCleanlooksStyle>
61 #include <QWindowsVistaStyle>
62 #include <QWindowsStyle>
63 #include <QSysInfo>
64 #include <QDragEnterEvent>
65 #include <QMimeData>
66 #include <QProcess>
67 #include <QUuid>
68 #include <QProcessEnvironment>
69 #include <QCryptographicHash>
70 #include <QTranslator>
71 #include <QResource>
72 #include <QScrollBar>
73
74 //System includes
75 #include <MMSystem.h>
76 #include <ShellAPI.h>
77
78 ////////////////////////////////////////////////////////////
79 // Helper macros
80 ////////////////////////////////////////////////////////////
81
82 #define ABORT_IF_BUSY do \
83 { \
84         if(m_banner->isVisible() || m_delayedFileTimer->isActive()) \
85         { \
86                 MessageBeep(MB_ICONEXCLAMATION); \
87                 return; \
88         } \
89 } \
90 while(0)
91
92 #define SET_TEXT_COLOR(WIDGET, COLOR) do \
93 { \
94         QPalette _palette = WIDGET->palette(); \
95         _palette.setColor(QPalette::WindowText, (COLOR)); \
96         _palette.setColor(QPalette::Text, (COLOR)); \
97         WIDGET->setPalette(_palette); \
98 } \
99 while(0)
100
101 #define SET_FONT_BOLD(WIDGET,BOLD) do \
102 { \
103         QFont _font = WIDGET->font(); \
104         _font.setBold(BOLD); \
105         WIDGET->setFont(_font); \
106 } \
107 while(0)
108
109 #define TEMP_HIDE_DROPBOX(CMD) do \
110 { \
111         bool _dropBoxVisible = m_dropBox->isVisible(); \
112         if(_dropBoxVisible) m_dropBox->hide(); \
113         do { CMD } while(0); \
114         if(_dropBoxVisible) m_dropBox->show(); \
115 } \
116 while(0)
117
118 #define SET_MODEL(VIEW, MODEL) do \
119 { \
120         QItemSelectionModel *_tmp = (VIEW)->selectionModel(); \
121         (VIEW)->setModel(MODEL); \
122         LAMEXP_DELETE(_tmp); \
123 } \
124 while(0)
125
126 #define SET_CHECKBOX_STATE(CHCKBX, STATE) do \
127 { \
128         if((CHCKBX)->isChecked() != (STATE)) \
129         { \
130                 (CHCKBX)->click(); \
131         } \
132         if((CHCKBX)->isChecked() != (STATE)) \
133         { \
134                 qWarning("Warning: Failed to set checkbox " #CHCKBX " state!"); \
135         } \
136 } \
137 while(0)
138
139 #define TRIM_STRING_RIGHT(STR) do \
140 { \
141         while((STR.length() > 0) && STR[STR.length()-1].isSpace()) STR.chop(1); \
142 } \
143 while(0)
144
145 #define LINK(URL) QString("<a href=\"%1\">%2</a>").arg(URL).arg(QString(URL).replace("-", "&minus;"))
146 #define FSLINK(PATH) QString("<a href=\"file:///%1\">%2</a>").arg(PATH).arg(QString(PATH).replace("-", "&minus;"))
147 #define USE_NATIVE_FILE_DIALOG (lamexp_themes_enabled() || ((QSysInfo::windowsVersion() & QSysInfo::WV_NT_based) < QSysInfo::WV_XP))
148 #define CENTER_CURRENT_OUTPUT_FOLDER_DELAYED QTimer::singleShot(125, this, SLOT(centerOutputFolderModel()))
149
150 static const DWORD IDM_ABOUTBOX = 0xEFF0;
151
152 ////////////////////////////////////////////////////////////
153 // Constructor
154 ////////////////////////////////////////////////////////////
155
156 MainWindow::MainWindow(FileListModel *fileListModel, AudioFileModel *metaInfo, SettingsModel *settingsModel, QWidget *parent)
157 :
158         QMainWindow(parent),
159         ui(new Ui::MainWindow),
160         m_fileListModel(fileListModel),
161         m_metaData(metaInfo),
162         m_settings(settingsModel),
163         m_fileSystemModel(NULL),
164         m_neroEncoderAvailable(lamexp_check_tool("neroAacEnc.exe") && lamexp_check_tool("neroAacDec.exe") && lamexp_check_tool("neroAacTag.exe")),
165         m_fhgEncoderAvailable(lamexp_check_tool("fhgaacenc.exe") && lamexp_check_tool("enc_fhgaac.dll") && lamexp_check_tool("nsutil.dll") && lamexp_check_tool("libmp4v2.dll")),
166         m_qaacEncoderAvailable(lamexp_check_tool("qaac.exe") && lamexp_check_tool("libsoxrate.dll")),
167         m_accepted(false),
168         m_firstTimeShown(true),
169         m_outputFolderViewCentering(false),
170         m_outputFolderViewInitCounter(0)
171 {
172         //Init the dialog, from the .ui file
173         ui->setupUi(this);
174         setWindowFlags(windowFlags() ^ Qt::WindowMaximizeButtonHint);
175         
176         //Register meta types
177         qRegisterMetaType<AudioFileModel>("AudioFileModel");
178
179         //Enabled main buttons
180         connect(ui->buttonAbout, SIGNAL(clicked()), this, SLOT(aboutButtonClicked()));
181         connect(ui->buttonStart, SIGNAL(clicked()), this, SLOT(encodeButtonClicked()));
182         connect(ui->buttonQuit, SIGNAL(clicked()), this, SLOT(closeButtonClicked()));
183
184         //Setup tab widget
185         ui->tabWidget->setCurrentIndex(0);
186         connect(ui->tabWidget, SIGNAL(currentChanged(int)), this, SLOT(tabPageChanged(int)));
187
188         //Add system menu
189         if(HMENU hMenu = ::GetSystemMenu(winId(), FALSE))
190         {
191                 AppendMenuW(hMenu, MF_SEPARATOR, 0, 0);
192                 AppendMenuW(hMenu, MF_STRING, IDM_ABOUTBOX, L"About...");
193         }
194
195         //--------------------------------
196         // Setup "Source" tab
197         //--------------------------------
198
199         ui->sourceFileView->setModel(m_fileListModel);
200         ui->sourceFileView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
201         ui->sourceFileView->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);
202         ui->sourceFileView->setContextMenuPolicy(Qt::CustomContextMenu);
203         ui->sourceFileView->viewport()->installEventFilter(this);
204         m_dropNoteLabel = new QLabel(ui->sourceFileView);
205         m_dropNoteLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
206         SET_FONT_BOLD(m_dropNoteLabel, true);
207         SET_TEXT_COLOR(m_dropNoteLabel, Qt::darkGray);
208         m_sourceFilesContextMenu = new QMenu();
209         m_showDetailsContextAction = m_sourceFilesContextMenu->addAction(QIcon(":/icons/zoom.png"), "N/A");
210         m_previewContextAction = m_sourceFilesContextMenu->addAction(QIcon(":/icons/sound.png"), "N/A");
211         m_findFileContextAction = m_sourceFilesContextMenu->addAction(QIcon(":/icons/folder_go.png"), "N/A");
212         m_sourceFilesContextMenu->addSeparator();
213         m_exportCsvContextAction = m_sourceFilesContextMenu->addAction(QIcon(":/icons/table_save.png"), "N/A");
214         m_importCsvContextAction = m_sourceFilesContextMenu->addAction(QIcon(":/icons/folder_table.png"), "N/A");
215         SET_FONT_BOLD(m_showDetailsContextAction, true);
216         connect(ui->buttonAddFiles, SIGNAL(clicked()), this, SLOT(addFilesButtonClicked()));
217         connect(ui->buttonRemoveFile, SIGNAL(clicked()), this, SLOT(removeFileButtonClicked()));
218         connect(ui->buttonClearFiles, SIGNAL(clicked()), this, SLOT(clearFilesButtonClicked()));
219         connect(ui->buttonFileUp, SIGNAL(clicked()), this, SLOT(fileUpButtonClicked()));
220         connect(ui->buttonFileDown, SIGNAL(clicked()), this, SLOT(fileDownButtonClicked()));
221         connect(ui->buttonShowDetails, SIGNAL(clicked()), this, SLOT(showDetailsButtonClicked()));
222         connect(m_fileListModel, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(sourceModelChanged()));
223         connect(m_fileListModel, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(sourceModelChanged()));
224         connect(m_fileListModel, SIGNAL(modelReset()), this, SLOT(sourceModelChanged()));
225         connect(ui->sourceFileView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(sourceFilesContextMenu(QPoint)));
226         connect(ui->sourceFileView->verticalScrollBar(), SIGNAL(sliderMoved(int)), this, SLOT(sourceFilesScrollbarMoved(int)));
227         connect(ui->sourceFileView->verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(sourceFilesScrollbarMoved(int)));
228         connect(m_showDetailsContextAction, SIGNAL(triggered(bool)), this, SLOT(showDetailsButtonClicked()));
229         connect(m_previewContextAction, SIGNAL(triggered(bool)), this, SLOT(previewContextActionTriggered()));
230         connect(m_findFileContextAction, SIGNAL(triggered(bool)), this, SLOT(findFileContextActionTriggered()));
231         connect(m_exportCsvContextAction, SIGNAL(triggered(bool)), this, SLOT(exportCsvContextActionTriggered()));
232         connect(m_importCsvContextAction, SIGNAL(triggered(bool)), this, SLOT(importCsvContextActionTriggered()));
233
234         //--------------------------------
235         // Setup "Output" tab
236         //--------------------------------
237
238         ui->outputFolderView->setHeaderHidden(true);
239         ui->outputFolderView->setAnimated(false);
240         ui->outputFolderView->setMouseTracking(false);
241         ui->outputFolderView->setContextMenuPolicy(Qt::CustomContextMenu);
242         ui->outputFolderView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
243
244         m_evenFilterOutputFolderMouse = new CustomEventFilter;
245         ui->outputFoldersEditorLabel->installEventFilter(m_evenFilterOutputFolderMouse);
246         ui->outputFoldersFovoritesLabel->installEventFilter(m_evenFilterOutputFolderMouse);
247         ui->outputFolderLabel->installEventFilter(m_evenFilterOutputFolderMouse);
248
249         m_evenFilterOutputFolderView = new CustomEventFilter;
250         ui->outputFolderView->installEventFilter(m_evenFilterOutputFolderView);
251
252         SET_CHECKBOX_STATE(ui->saveToSourceFolderCheckBox, m_settings->outputToSourceDir());
253         ui->prependRelativePathCheckBox->setChecked(m_settings->prependRelativeSourcePath());
254         
255         connect(ui->outputFolderView, SIGNAL(clicked(QModelIndex)), this, SLOT(outputFolderViewClicked(QModelIndex)));
256         connect(ui->outputFolderView, SIGNAL(activated(QModelIndex)), this, SLOT(outputFolderViewClicked(QModelIndex)));
257         connect(ui->outputFolderView, SIGNAL(pressed(QModelIndex)), this, SLOT(outputFolderViewClicked(QModelIndex)));
258         connect(ui->outputFolderView, SIGNAL(entered(QModelIndex)), this, SLOT(outputFolderViewMoved(QModelIndex)));
259         connect(ui->outputFolderView, SIGNAL(expanded(QModelIndex)), this, SLOT(outputFolderItemExpanded(QModelIndex)));
260         connect(ui->buttonMakeFolder, SIGNAL(clicked()), this, SLOT(makeFolderButtonClicked()));
261         connect(ui->buttonGotoHome, SIGNAL(clicked()), SLOT(gotoHomeFolderButtonClicked()));
262         connect(ui->buttonGotoDesktop, SIGNAL(clicked()), this, SLOT(gotoDesktopButtonClicked()));
263         connect(ui->buttonGotoMusic, SIGNAL(clicked()), this, SLOT(gotoMusicFolderButtonClicked()));
264         connect(ui->saveToSourceFolderCheckBox, SIGNAL(clicked()), this, SLOT(saveToSourceFolderChanged()));
265         connect(ui->prependRelativePathCheckBox, SIGNAL(clicked()), this, SLOT(prependRelativePathChanged()));
266         connect(ui->outputFolderEdit, SIGNAL(editingFinished()), this, SLOT(outputFolderEditFinished()));
267         connect(m_evenFilterOutputFolderMouse, SIGNAL(eventOccurred(QWidget*, QEvent*)), this, SLOT(outputFolderMouseEventOccurred(QWidget*, QEvent*)));
268         connect(m_evenFilterOutputFolderView, SIGNAL(eventOccurred(QWidget*, QEvent*)), this, SLOT(outputFolderViewEventOccurred(QWidget*, QEvent*)));
269
270         if(m_outputFolderContextMenu = new QMenu())
271         {
272                 m_showFolderContextAction = m_outputFolderContextMenu->addAction(QIcon(":/icons/zoom.png"), "N/A");
273                 m_refreshFolderContextAction = m_outputFolderContextMenu->addAction(QIcon(":/icons/arrow_refresh.png"), "N/A");
274                 m_outputFolderContextMenu->setDefaultAction(m_showFolderContextAction);
275                 connect(ui->outputFolderView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(outputFolderContextMenu(QPoint)));
276                 connect(m_showFolderContextAction, SIGNAL(triggered(bool)), this, SLOT(showFolderContextActionTriggered()));
277                 connect(m_refreshFolderContextAction, SIGNAL(triggered(bool)), this, SLOT(refreshFolderContextActionTriggered()));
278         }
279
280         if(m_outputFolderFavoritesMenu = new QMenu())
281         {
282                 m_addFavoriteFolderAction = m_outputFolderFavoritesMenu->addAction(QIcon(":/icons/add.png"), "N/A");
283                 m_outputFolderFavoritesMenu->insertSeparator(m_addFavoriteFolderAction);
284                 connect(m_addFavoriteFolderAction, SIGNAL(triggered(bool)), this, SLOT(addFavoriteFolderActionTriggered()));
285         }
286
287         ui->outputFolderEdit->setVisible(false);
288         if(m_outputFolderNoteBox = new QLabel(ui->outputFolderView))
289         {
290                 m_outputFolderNoteBox->setAutoFillBackground(true);
291                 m_outputFolderNoteBox->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
292                 m_outputFolderNoteBox->setFrameShape(QFrame::StyledPanel);
293                 SET_FONT_BOLD(m_outputFolderNoteBox, true);
294                 m_outputFolderNoteBox->hide();
295
296         }
297
298         outputFolderViewClicked(QModelIndex());
299         refreshFavorites();
300         
301         //--------------------------------
302         // Setup "Meta Data" tab
303         //--------------------------------
304
305         m_metaInfoModel = new MetaInfoModel(m_metaData, 6);
306         m_metaInfoModel->clearData();
307         m_metaInfoModel->setData(m_metaInfoModel->index(4, 1), m_settings->metaInfoPosition());
308         ui->metaDataView->setModel(m_metaInfoModel);
309         ui->metaDataView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
310         ui->metaDataView->verticalHeader()->hide();
311         ui->metaDataView->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);
312         SET_CHECKBOX_STATE(ui->writeMetaDataCheckBox, m_settings->writeMetaTags());
313         ui->generatePlaylistCheckBox->setChecked(m_settings->createPlaylist());
314         connect(ui->buttonEditMeta, SIGNAL(clicked()), this, SLOT(editMetaButtonClicked()));
315         connect(ui->buttonClearMeta, SIGNAL(clicked()), this, SLOT(clearMetaButtonClicked()));
316         connect(ui->writeMetaDataCheckBox, SIGNAL(clicked()), this, SLOT(metaTagsEnabledChanged()));
317         connect(ui->generatePlaylistCheckBox, SIGNAL(clicked()), this, SLOT(playlistEnabledChanged()));
318
319         //--------------------------------
320         //Setup "Compression" tab
321         //--------------------------------
322
323         m_encoderButtonGroup = new QButtonGroup(this);
324         m_encoderButtonGroup->addButton(ui->radioButtonEncoderMP3, SettingsModel::MP3Encoder);
325         m_encoderButtonGroup->addButton(ui->radioButtonEncoderVorbis, SettingsModel::VorbisEncoder);
326         m_encoderButtonGroup->addButton(ui->radioButtonEncoderAAC, SettingsModel::AACEncoder);
327         m_encoderButtonGroup->addButton(ui->radioButtonEncoderAC3, SettingsModel::AC3Encoder);
328         m_encoderButtonGroup->addButton(ui->radioButtonEncoderFLAC, SettingsModel::FLACEncoder);
329         m_encoderButtonGroup->addButton(ui->radioButtonEncoderOpus, SettingsModel::OpusEncoder);
330         m_encoderButtonGroup->addButton(ui->radioButtonEncoderDCA, SettingsModel::DCAEncoder);
331         m_encoderButtonGroup->addButton(ui->radioButtonEncoderPCM, SettingsModel::PCMEncoder);
332
333         m_modeButtonGroup = new QButtonGroup(this);
334         m_modeButtonGroup->addButton(ui->radioButtonModeQuality, SettingsModel::VBRMode);
335         m_modeButtonGroup->addButton(ui->radioButtonModeAverageBitrate, SettingsModel::ABRMode);
336         m_modeButtonGroup->addButton(ui->radioButtonConstBitrate, SettingsModel::CBRMode);
337
338         ui->radioButtonEncoderAAC->setEnabled(m_neroEncoderAvailable || m_fhgEncoderAvailable || m_qaacEncoderAvailable);
339         ui->radioButtonEncoderMP3->setChecked(m_settings->compressionEncoder() == SettingsModel::MP3Encoder);
340         ui->radioButtonEncoderVorbis->setChecked(m_settings->compressionEncoder() == SettingsModel::VorbisEncoder);
341         ui->radioButtonEncoderAAC->setChecked((m_settings->compressionEncoder() == SettingsModel::AACEncoder) && (m_neroEncoderAvailable || m_fhgEncoderAvailable || m_qaacEncoderAvailable));
342         ui->radioButtonEncoderAC3->setChecked(m_settings->compressionEncoder() == SettingsModel::AC3Encoder);
343         ui->radioButtonEncoderFLAC->setChecked(m_settings->compressionEncoder() == SettingsModel::FLACEncoder);
344         ui->radioButtonEncoderOpus->setChecked(m_settings->compressionEncoder() == SettingsModel::OpusEncoder);
345         ui->radioButtonEncoderDCA->setChecked(m_settings->compressionEncoder() == SettingsModel::DCAEncoder);
346         ui->radioButtonEncoderPCM->setChecked(m_settings->compressionEncoder() == SettingsModel::PCMEncoder);
347         ui->radioButtonModeQuality->setChecked(m_settings->compressionRCMode() == SettingsModel::VBRMode);
348         ui->radioButtonModeAverageBitrate->setChecked(m_settings->compressionRCMode() == SettingsModel::ABRMode);
349         ui->radioButtonConstBitrate->setChecked(m_settings->compressionRCMode() == SettingsModel::CBRMode);
350         ui->sliderBitrate->setValue(m_settings->compressionBitrate());
351         
352         m_evenFilterCompressionTab = new CustomEventFilter();
353         ui->labelCompressionHelp->installEventFilter(m_evenFilterCompressionTab);
354
355         connect(m_encoderButtonGroup, SIGNAL(buttonClicked(int)), this, SLOT(updateEncoder(int)));
356         connect(m_modeButtonGroup, SIGNAL(buttonClicked(int)), this, SLOT(updateRCMode(int)));
357         connect(m_evenFilterCompressionTab, SIGNAL(eventOccurred(QWidget*, QEvent*)), this, SLOT(compressionTabEventOccurred(QWidget*, QEvent*)));
358         connect(ui->sliderBitrate, SIGNAL(valueChanged(int)), this, SLOT(updateBitrate(int)));
359
360         updateEncoder(m_encoderButtonGroup->checkedId());
361
362         //--------------------------------
363         //Setup "Advanced Options" tab
364         //--------------------------------
365
366         ui->sliderLameAlgoQuality->setValue(m_settings->lameAlgoQuality());
367         if(m_settings->maximumInstances() > 0) ui->sliderMaxInstances->setValue(m_settings->maximumInstances());
368
369         ui->spinBoxBitrateManagementMin->setValue(m_settings->bitrateManagementMinRate());
370         ui->spinBoxBitrateManagementMax->setValue(m_settings->bitrateManagementMaxRate());
371         ui->spinBoxNormalizationFilter->setValue(static_cast<double>(m_settings->normalizationFilterMaxVolume()) / 100.0);
372         ui->spinBoxToneAdjustBass->setValue(static_cast<double>(m_settings->toneAdjustBass()) / 100.0);
373         ui->spinBoxToneAdjustTreble->setValue(static_cast<double>(m_settings->toneAdjustTreble()) / 100.0);
374         ui->spinBoxAftenSearchSize->setValue(m_settings->aftenExponentSearchSize());
375         ui->spinBoxOpusComplexity->setValue(m_settings->opusComplexity());
376         
377         ui->comboBoxMP3ChannelMode->setCurrentIndex(m_settings->lameChannelMode());
378         ui->comboBoxSamplingRate->setCurrentIndex(m_settings->samplingRate());
379         ui->comboBoxAACProfile->setCurrentIndex(m_settings->aacEncProfile());
380         ui->comboBoxAftenCodingMode->setCurrentIndex(m_settings->aftenAudioCodingMode());
381         ui->comboBoxAftenDRCMode->setCurrentIndex(m_settings->aftenDynamicRangeCompression());
382         ui->comboBoxNormalizationMode->setCurrentIndex(m_settings->normalizationFilterEqualizationMode());
383         //comboBoxOpusOptimize->setCurrentIndex(m_settings->opusOptimizeFor());
384         ui->comboBoxOpusFramesize->setCurrentIndex(m_settings->opusFramesize());
385         
386         SET_CHECKBOX_STATE(ui->checkBoxBitrateManagement, m_settings->bitrateManagementEnabled());
387         SET_CHECKBOX_STATE(ui->checkBoxNeroAAC2PassMode, m_settings->neroAACEnable2Pass());
388         SET_CHECKBOX_STATE(ui->checkBoxAftenFastAllocation, m_settings->aftenFastBitAllocation());
389         SET_CHECKBOX_STATE(ui->checkBoxNormalizationFilter, m_settings->normalizationFilterEnabled());
390         SET_CHECKBOX_STATE(ui->checkBoxAutoDetectInstances, (m_settings->maximumInstances() < 1));
391         SET_CHECKBOX_STATE(ui->checkBoxUseSystemTempFolder, !m_settings->customTempPathEnabled());
392         SET_CHECKBOX_STATE(ui->checkBoxRenameOutput, m_settings->renameOutputFilesEnabled());
393         SET_CHECKBOX_STATE(ui->checkBoxForceStereoDownmix, m_settings->forceStereoDownmix());
394         ui->checkBoxNeroAAC2PassMode->setEnabled(!(m_fhgEncoderAvailable || m_qaacEncoderAvailable));
395         
396         ui->lineEditCustomParamLAME->setText(m_settings->customParametersLAME());
397         ui->lineEditCustomParamOggEnc->setText(m_settings->customParametersOggEnc());
398         ui->lineEditCustomParamNeroAAC->setText(m_settings->customParametersAacEnc());
399         ui->lineEditCustomParamFLAC->setText(m_settings->customParametersFLAC());
400         ui->lineEditCustomParamAften->setText(m_settings->customParametersAften());
401         ui->lineEditCustomParamOpus->setText(m_settings->customParametersOpus());
402         ui->lineEditCustomTempFolder->setText(QDir::toNativeSeparators(m_settings->customTempPath()));
403         ui->lineEditRenamePattern->setText(m_settings->renameOutputFilesPattern());
404         
405         m_evenFilterCustumParamsHelp = new CustomEventFilter();
406         ui->helpCustomParamLAME->installEventFilter(m_evenFilterCustumParamsHelp);
407         ui->helpCustomParamOggEnc->installEventFilter(m_evenFilterCustumParamsHelp);
408         ui->helpCustomParamNeroAAC->installEventFilter(m_evenFilterCustumParamsHelp);
409         ui->helpCustomParamFLAC->installEventFilter(m_evenFilterCustumParamsHelp);
410         ui->helpCustomParamAften->installEventFilter(m_evenFilterCustumParamsHelp);
411         ui->helpCustomParamOpus->installEventFilter(m_evenFilterCustumParamsHelp);
412         
413         m_overwriteButtonGroup = new QButtonGroup(this);
414         m_overwriteButtonGroup->addButton(ui->radioButtonOverwriteModeKeepBoth, SettingsModel::Overwrite_KeepBoth);
415         m_overwriteButtonGroup->addButton(ui->radioButtonOverwriteModeSkipFile, SettingsModel::Overwrite_SkipFile);
416         m_overwriteButtonGroup->addButton(ui->radioButtonOverwriteModeReplaces, SettingsModel::Overwrite_Replaces);
417
418         ui->radioButtonOverwriteModeKeepBoth->setChecked(m_settings->overwriteMode() == SettingsModel::Overwrite_KeepBoth);
419         ui->radioButtonOverwriteModeSkipFile->setChecked(m_settings->overwriteMode() == SettingsModel::Overwrite_SkipFile);
420         ui->radioButtonOverwriteModeReplaces->setChecked(m_settings->overwriteMode() == SettingsModel::Overwrite_Replaces);
421
422         connect(ui->sliderLameAlgoQuality, SIGNAL(valueChanged(int)), this, SLOT(updateLameAlgoQuality(int)));
423         connect(ui->checkBoxBitrateManagement, SIGNAL(clicked(bool)), this, SLOT(bitrateManagementEnabledChanged(bool)));
424         connect(ui->spinBoxBitrateManagementMin, SIGNAL(valueChanged(int)), this, SLOT(bitrateManagementMinChanged(int)));
425         connect(ui->spinBoxBitrateManagementMax, SIGNAL(valueChanged(int)), this, SLOT(bitrateManagementMaxChanged(int)));
426         connect(ui->comboBoxMP3ChannelMode, SIGNAL(currentIndexChanged(int)), this, SLOT(channelModeChanged(int)));
427         connect(ui->comboBoxSamplingRate, SIGNAL(currentIndexChanged(int)), this, SLOT(samplingRateChanged(int)));
428         connect(ui->checkBoxNeroAAC2PassMode, SIGNAL(clicked(bool)), this, SLOT(neroAAC2PassChanged(bool)));
429         connect(ui->comboBoxAACProfile, SIGNAL(currentIndexChanged(int)), this, SLOT(neroAACProfileChanged(int)));
430         connect(ui->checkBoxNormalizationFilter, SIGNAL(clicked(bool)), this, SLOT(normalizationEnabledChanged(bool)));
431         connect(ui->comboBoxAftenCodingMode, SIGNAL(currentIndexChanged(int)), this, SLOT(aftenCodingModeChanged(int)));
432         connect(ui->comboBoxAftenDRCMode, SIGNAL(currentIndexChanged(int)), this, SLOT(aftenDRCModeChanged(int)));
433         connect(ui->spinBoxAftenSearchSize, SIGNAL(valueChanged(int)), this, SLOT(aftenSearchSizeChanged(int)));
434         connect(ui->checkBoxAftenFastAllocation, SIGNAL(clicked(bool)), this, SLOT(aftenFastAllocationChanged(bool)));
435         connect(ui->spinBoxNormalizationFilter, SIGNAL(valueChanged(double)), this, SLOT(normalizationMaxVolumeChanged(double)));
436         connect(ui->comboBoxNormalizationMode, SIGNAL(currentIndexChanged(int)), this, SLOT(normalizationModeChanged(int)));
437         connect(ui->spinBoxToneAdjustBass, SIGNAL(valueChanged(double)), this, SLOT(toneAdjustBassChanged(double)));
438         connect(ui->spinBoxToneAdjustTreble, SIGNAL(valueChanged(double)), this, SLOT(toneAdjustTrebleChanged(double)));
439         connect(ui->buttonToneAdjustReset, SIGNAL(clicked()), this, SLOT(toneAdjustTrebleReset()));
440         connect(ui->lineEditCustomParamLAME, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
441         connect(ui->lineEditCustomParamOggEnc, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
442         connect(ui->lineEditCustomParamNeroAAC, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
443         connect(ui->lineEditCustomParamFLAC, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
444         connect(ui->lineEditCustomParamAften, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
445         connect(ui->lineEditCustomParamOpus, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
446         connect(ui->sliderMaxInstances, SIGNAL(valueChanged(int)), this, SLOT(updateMaximumInstances(int)));
447         connect(ui->checkBoxAutoDetectInstances, SIGNAL(clicked(bool)), this, SLOT(autoDetectInstancesChanged(bool)));
448         connect(ui->buttonBrowseCustomTempFolder, SIGNAL(clicked()), this, SLOT(browseCustomTempFolderButtonClicked()));
449         connect(ui->lineEditCustomTempFolder, SIGNAL(textChanged(QString)), this, SLOT(customTempFolderChanged(QString)));
450         connect(ui->checkBoxUseSystemTempFolder, SIGNAL(clicked(bool)), this, SLOT(useCustomTempFolderChanged(bool)));
451         connect(ui->buttonResetAdvancedOptions, SIGNAL(clicked()), this, SLOT(resetAdvancedOptionsButtonClicked()));
452         connect(ui->checkBoxRenameOutput, SIGNAL(clicked(bool)), this, SLOT(renameOutputEnabledChanged(bool)));
453         connect(ui->lineEditRenamePattern, SIGNAL(editingFinished()), this, SLOT(renameOutputPatternChanged()));
454         connect(ui->lineEditRenamePattern, SIGNAL(textChanged(QString)), this, SLOT(renameOutputPatternChanged(QString)));
455         connect(ui->labelShowRenameMacros, SIGNAL(linkActivated(QString)), this, SLOT(showRenameMacros(QString)));
456         connect(ui->checkBoxForceStereoDownmix, SIGNAL(clicked(bool)), this, SLOT(forceStereoDownmixEnabledChanged(bool)));
457         connect(ui->comboBoxOpusFramesize, SIGNAL(currentIndexChanged(int)), this, SLOT(opusSettingsChanged()));
458         connect(ui->spinBoxOpusComplexity, SIGNAL(valueChanged(int)), this, SLOT(opusSettingsChanged()));
459         //connect(comboBoxOpusOptimize, SIGNAL(currentIndexChanged(int)), SLOT(opusSettingsChanged()));
460         //connect(checkBoxOpusExpAnalysis, SIGNAL(clicked(bool)), this, SLOT(opusSettingsChanged()));
461         connect(m_overwriteButtonGroup, SIGNAL(buttonClicked(int)), this, SLOT(overwriteModeChanged(int)));
462         connect(m_evenFilterCustumParamsHelp, SIGNAL(eventOccurred(QWidget*, QEvent*)), this, SLOT(customParamsHelpRequested(QWidget*, QEvent*)));
463
464         //--------------------------------
465         // Force initial GUI update
466         //--------------------------------
467
468         updateLameAlgoQuality(ui->sliderLameAlgoQuality->value());
469         updateMaximumInstances(ui->sliderMaxInstances->value());
470         toneAdjustTrebleChanged(ui->spinBoxToneAdjustTreble->value());
471         toneAdjustBassChanged(ui->spinBoxToneAdjustBass->value());
472         customParamsChanged();
473         
474         //--------------------------------
475         // Initialize actions
476         //--------------------------------
477
478         //Activate file menu actions
479         ui->actionOpenFolder->setData(QVariant::fromValue<bool>(false));
480         ui->actionOpenFolderRecursively->setData(QVariant::fromValue<bool>(true));
481         connect(ui->actionOpenFolder, SIGNAL(triggered()), this, SLOT(openFolderActionActivated()));
482         connect(ui->actionOpenFolderRecursively, SIGNAL(triggered()), this, SLOT(openFolderActionActivated()));
483
484         //Activate view menu actions
485         m_tabActionGroup = new QActionGroup(this);
486         m_tabActionGroup->addAction(ui->actionSourceFiles);
487         m_tabActionGroup->addAction(ui->actionOutputDirectory);
488         m_tabActionGroup->addAction(ui->actionCompression);
489         m_tabActionGroup->addAction(ui->actionMetaData);
490         m_tabActionGroup->addAction(ui->actionAdvancedOptions);
491         ui->actionSourceFiles->setData(0);
492         ui->actionOutputDirectory->setData(1);
493         ui->actionMetaData->setData(2);
494         ui->actionCompression->setData(3);
495         ui->actionAdvancedOptions->setData(4);
496         ui->actionSourceFiles->setChecked(true);
497         connect(m_tabActionGroup, SIGNAL(triggered(QAction*)), this, SLOT(tabActionActivated(QAction*)));
498
499         //Activate style menu actions
500         m_styleActionGroup = new QActionGroup(this);
501         m_styleActionGroup->addAction(ui->actionStylePlastique);
502         m_styleActionGroup->addAction(ui->actionStyleCleanlooks);
503         m_styleActionGroup->addAction(ui->actionStyleWindowsVista);
504         m_styleActionGroup->addAction(ui->actionStyleWindowsXP);
505         m_styleActionGroup->addAction(ui->actionStyleWindowsClassic);
506         ui->actionStylePlastique->setData(0);
507         ui->actionStyleCleanlooks->setData(1);
508         ui->actionStyleWindowsVista->setData(2);
509         ui->actionStyleWindowsXP->setData(3);
510         ui->actionStyleWindowsClassic->setData(4);
511         ui->actionStylePlastique->setChecked(true);
512         ui->actionStyleWindowsXP->setEnabled((QSysInfo::windowsVersion() & QSysInfo::WV_NT_based) >= QSysInfo::WV_XP && lamexp_themes_enabled());
513         ui->actionStyleWindowsVista->setEnabled((QSysInfo::windowsVersion() & QSysInfo::WV_NT_based) >= QSysInfo::WV_VISTA && lamexp_themes_enabled());
514         connect(m_styleActionGroup, SIGNAL(triggered(QAction*)), this, SLOT(styleActionActivated(QAction*)));
515         styleActionActivated(NULL);
516
517         //Populate the language menu
518         m_languageActionGroup = new QActionGroup(this);
519         QStringList translations = lamexp_query_translations();
520         while(!translations.isEmpty())
521         {
522                 QString langId = translations.takeFirst();
523                 QAction *currentLanguage = new QAction(this);
524                 currentLanguage->setData(langId);
525                 currentLanguage->setText(lamexp_translation_name(langId));
526                 currentLanguage->setIcon(QIcon(QString(":/flags/%1.png").arg(langId)));
527                 currentLanguage->setCheckable(true);
528                 currentLanguage->setChecked(false);
529                 m_languageActionGroup->addAction(currentLanguage);
530                 ui->menuLanguage->insertAction(ui->actionLoadTranslationFromFile, currentLanguage);
531         }
532         ui->menuLanguage->insertSeparator(ui->actionLoadTranslationFromFile);
533         connect(ui->actionLoadTranslationFromFile, SIGNAL(triggered(bool)), this, SLOT(languageFromFileActionActivated(bool)));
534         connect(m_languageActionGroup, SIGNAL(triggered(QAction*)), this, SLOT(languageActionActivated(QAction*)));
535         ui->actionLoadTranslationFromFile->setChecked(false);
536
537         //Activate tools menu actions
538         ui->actionDisableUpdateReminder->setChecked(!m_settings->autoUpdateEnabled());
539         ui->actionDisableSounds->setChecked(!m_settings->soundsEnabled());
540         ui->actionDisableNeroAacNotifications->setChecked(!m_settings->neroAacNotificationsEnabled());
541         ui->actionDisableSlowStartupNotifications->setChecked(!m_settings->antivirNotificationsEnabled());
542         ui->actionDisableShellIntegration->setChecked(!m_settings->shellIntegrationEnabled());
543         ui->actionDisableShellIntegration->setDisabled(lamexp_portable_mode() && ui->actionDisableShellIntegration->isChecked());
544         ui->actionCheckForBetaUpdates->setChecked(m_settings->autoUpdateCheckBeta() || lamexp_version_demo());
545         ui->actionCheckForBetaUpdates->setEnabled(!lamexp_version_demo());
546         ui->actionHibernateComputer->setChecked(m_settings->hibernateComputer());
547         ui->actionHibernateComputer->setEnabled(lamexp_is_hibernation_supported());
548         connect(ui->actionDisableUpdateReminder, SIGNAL(triggered(bool)), this, SLOT(disableUpdateReminderActionTriggered(bool)));
549         connect(ui->actionDisableSounds, SIGNAL(triggered(bool)), this, SLOT(disableSoundsActionTriggered(bool)));
550         connect(ui->actionDisableNeroAacNotifications, SIGNAL(triggered(bool)), this, SLOT(disableNeroAacNotificationsActionTriggered(bool)));
551         connect(ui->actionDisableSlowStartupNotifications, SIGNAL(triggered(bool)), this, SLOT(disableSlowStartupNotificationsActionTriggered(bool)));
552         connect(ui->actionDisableShellIntegration, SIGNAL(triggered(bool)), this, SLOT(disableShellIntegrationActionTriggered(bool)));
553         connect(ui->actionShowDropBoxWidget, SIGNAL(triggered(bool)), this, SLOT(showDropBoxWidgetActionTriggered(bool)));
554         connect(ui->actionHibernateComputer, SIGNAL(triggered(bool)), this, SLOT(hibernateComputerActionTriggered(bool)));
555         connect(ui->actionCheckForBetaUpdates, SIGNAL(triggered(bool)), this, SLOT(checkForBetaUpdatesActionTriggered(bool)));
556         connect(ui->actionImportCueSheet, SIGNAL(triggered(bool)), this, SLOT(importCueSheetActionTriggered(bool)));
557                 
558         //Activate help menu actions
559         ui->actionVisitHomepage->setData(QString::fromLatin1(lamexp_website_url()));
560         ui->actionVisitSupport->setData(QString::fromLatin1(lamexp_support_url()));
561         ui->actionDocumentFAQ->setData(QString("%1/FAQ.html").arg(QApplication::applicationDirPath()));
562         ui->actionDocumentChangelog->setData(QString("%1/Changelog.html").arg(QApplication::applicationDirPath()));
563         ui->actionDocumentTranslate->setData(QString("%1/Translate.html").arg(QApplication::applicationDirPath()));
564         connect(ui->actionCheckUpdates, SIGNAL(triggered()), this, SLOT(checkUpdatesActionActivated()));
565         connect(ui->actionVisitHomepage, SIGNAL(triggered()), this, SLOT(visitHomepageActionActivated()));
566         connect(ui->actionVisitSupport, SIGNAL(triggered()), this, SLOT(visitHomepageActionActivated()));
567         connect(ui->actionDocumentFAQ, SIGNAL(triggered()), this, SLOT(documentActionActivated()));
568         connect(ui->actionDocumentChangelog, SIGNAL(triggered()), this, SLOT(documentActionActivated()));
569         connect(ui->actionDocumentTranslate, SIGNAL(triggered()), this, SLOT(documentActionActivated()));
570         
571         //--------------------------------
572         // Prepare to show window
573         //--------------------------------
574
575         //Center window in screen
576         QRect desktopRect = QApplication::desktop()->screenGeometry();
577         QRect thisRect = this->geometry();
578         move((desktopRect.width() - thisRect.width()) / 2, (desktopRect.height() - thisRect.height()) / 2);
579         setMinimumSize(thisRect.width(), thisRect.height());
580
581         //Create banner
582         m_banner = new WorkingBanner(this);
583
584         //Create DropBox widget
585         m_dropBox = new DropBox(this, m_fileListModel, m_settings);
586         connect(m_fileListModel, SIGNAL(modelReset()), m_dropBox, SLOT(modelChanged()));
587         connect(m_fileListModel, SIGNAL(rowsInserted(QModelIndex,int,int)), m_dropBox, SLOT(modelChanged()));
588         connect(m_fileListModel, SIGNAL(rowsRemoved(QModelIndex,int,int)), m_dropBox, SLOT(modelChanged()));
589         connect(m_fileListModel, SIGNAL(rowAppended()), m_dropBox, SLOT(modelChanged()));
590
591         //Create message handler thread
592         m_messageHandler = new MessageHandlerThread();
593         m_delayedFileList = new QStringList();
594         m_delayedFileTimer = new QTimer();
595         m_delayedFileTimer->setSingleShot(true);
596         m_delayedFileTimer->setInterval(5000);
597         connect(m_messageHandler, SIGNAL(otherInstanceDetected()), this, SLOT(notifyOtherInstance()), Qt::QueuedConnection);
598         connect(m_messageHandler, SIGNAL(fileReceived(QString)), this, SLOT(addFileDelayed(QString)), Qt::QueuedConnection);
599         connect(m_messageHandler, SIGNAL(folderReceived(QString, bool)), this, SLOT(addFolderDelayed(QString, bool)), Qt::QueuedConnection);
600         connect(m_messageHandler, SIGNAL(killSignalReceived()), this, SLOT(close()), Qt::QueuedConnection);
601         connect(m_delayedFileTimer, SIGNAL(timeout()), this, SLOT(handleDelayedFiles()));
602         m_messageHandler->start();
603
604         //Load translation
605         initializeTranslation();
606
607         //Re-translate (make sure we translate once)
608         QEvent languageChangeEvent(QEvent::LanguageChange);
609         changeEvent(&languageChangeEvent);
610
611         //Enable Drag & Drop
612         this->setAcceptDrops(true);
613 }
614
615 ////////////////////////////////////////////////////////////
616 // Destructor
617 ////////////////////////////////////////////////////////////
618
619 MainWindow::~MainWindow(void)
620 {
621         //Stop message handler thread
622         if(m_messageHandler && m_messageHandler->isRunning())
623         {
624                 m_messageHandler->stop();
625                 if(!m_messageHandler->wait(2500))
626                 {
627                         m_messageHandler->terminate();
628                         m_messageHandler->wait();
629                 }
630         }
631
632         //Unset models
633         SET_MODEL(ui->sourceFileView, NULL);
634         SET_MODEL(ui->outputFolderView, NULL);
635         SET_MODEL(ui->metaDataView, NULL);
636
637         //Free memory
638         LAMEXP_DELETE(m_tabActionGroup);
639         LAMEXP_DELETE(m_styleActionGroup);
640         LAMEXP_DELETE(m_languageActionGroup);
641         LAMEXP_DELETE(m_banner);
642         LAMEXP_DELETE(m_fileSystemModel);
643         LAMEXP_DELETE(m_messageHandler);
644         LAMEXP_DELETE(m_delayedFileList);
645         LAMEXP_DELETE(m_delayedFileTimer);
646         LAMEXP_DELETE(m_metaInfoModel);
647         LAMEXP_DELETE(m_encoderButtonGroup);
648         LAMEXP_DELETE(m_modeButtonGroup);
649         LAMEXP_DELETE(m_overwriteButtonGroup);
650         LAMEXP_DELETE(m_sourceFilesContextMenu);
651         LAMEXP_DELETE(m_outputFolderFavoritesMenu);
652         LAMEXP_DELETE(m_outputFolderContextMenu);
653         LAMEXP_DELETE(m_dropBox);
654         LAMEXP_DELETE(m_evenFilterCustumParamsHelp);
655         LAMEXP_DELETE(m_evenFilterOutputFolderMouse);
656         LAMEXP_DELETE(m_evenFilterOutputFolderView);
657         LAMEXP_DELETE(m_evenFilterCompressionTab);
658         
659         //Un-initialize the dialog
660         LAMEXP_DELETE(ui);
661 }
662
663 ////////////////////////////////////////////////////////////
664 // PRIVATE FUNCTIONS
665 ////////////////////////////////////////////////////////////
666
667 /*
668  * Add file to source list
669  */
670 void MainWindow::addFiles(const QStringList &files)
671 {
672         if(files.isEmpty())
673         {
674                 return;
675         }
676
677         ui->tabWidget->setCurrentIndex(0);
678
679         FileAnalyzer *analyzer = new FileAnalyzer(files);
680         connect(analyzer, SIGNAL(fileSelected(QString)), m_banner, SLOT(setText(QString)), Qt::QueuedConnection);
681         connect(analyzer, SIGNAL(progressValChanged(unsigned int)), m_banner, SLOT(setProgressVal(unsigned int)), Qt::QueuedConnection);
682         connect(analyzer, SIGNAL(progressMaxChanged(unsigned int)), m_banner, SLOT(setProgressMax(unsigned int)), Qt::QueuedConnection);
683         connect(analyzer, SIGNAL(fileAnalyzed(AudioFileModel)), m_fileListModel, SLOT(addFile(AudioFileModel)), Qt::QueuedConnection);
684         connect(m_banner, SIGNAL(userAbort()), analyzer, SLOT(abortProcess()), Qt::DirectConnection);
685
686         try
687         {
688                 m_fileListModel->setBlockUpdates(true);
689                 QTime startTime = QTime::currentTime();
690                 m_banner->show(tr("Adding file(s), please wait..."), analyzer);
691         }
692         catch(...)
693         {
694                 /* ignore any exceptions that may occur */
695         }
696
697         m_fileListModel->setBlockUpdates(false);
698         qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
699         ui->sourceFileView->update();
700         qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
701         ui->sourceFileView->scrollToBottom();
702         qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
703
704         if(analyzer->filesDenied())
705         {
706                 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."))));
707         }
708         if(analyzer->filesDummyCDDA())
709         {
710                 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>"))));
711         }
712         if(analyzer->filesCueSheet())
713         {
714                 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."))));
715         }
716         if(analyzer->filesRejected())
717         {
718                 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."))));
719         }
720
721         LAMEXP_DELETE(analyzer);
722         m_banner->close();
723 }
724
725 /*
726  * Add folder to source list
727  */
728 void MainWindow::addFolder(const QString &path, bool recursive, bool delayed)
729 {
730         QFileInfoList folderInfoList;
731         folderInfoList << QFileInfo(path);
732         QStringList fileList;
733         
734         m_banner->show(tr("Scanning folder(s) for files, please wait..."));
735         
736         QApplication::processEvents();
737         GetAsyncKeyState(VK_ESCAPE);
738
739         while(!folderInfoList.isEmpty())
740         {
741                 if(GetAsyncKeyState(VK_ESCAPE) & 0x0001)
742                 {
743                         MessageBeep(MB_ICONERROR);
744                         qWarning("Operation cancelled by user!");
745                         fileList.clear();
746                         break;
747                 }
748                 
749                 QDir currentDir(folderInfoList.takeFirst().canonicalFilePath());
750                 QFileInfoList fileInfoList = currentDir.entryInfoList(QDir::Files | QDir::NoSymLinks);
751
752                 while(!fileInfoList.isEmpty())
753                 {
754                         fileList << fileInfoList.takeFirst().canonicalFilePath();
755                 }
756
757                 QApplication::processEvents();
758
759                 if(recursive)
760                 {
761                         folderInfoList.append(currentDir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks));
762                         QApplication::processEvents();
763                 }
764         }
765         
766         m_banner->close();
767         QApplication::processEvents();
768
769         if(!fileList.isEmpty())
770         {
771                 if(delayed)
772                 {
773                         addFilesDelayed(fileList);
774                 }
775                 else
776                 {
777                         addFiles(fileList);
778                 }
779         }
780 }
781
782 /*
783  * Check for updates
784  */
785 bool MainWindow::checkForUpdates(void)
786 {
787         bool bReadyToInstall = false;
788         
789         UpdateDialog *updateDialog = new UpdateDialog(m_settings, this);
790         updateDialog->exec();
791
792         if(updateDialog->getSuccess())
793         {
794                 m_settings->autoUpdateLastCheck(QDate::currentDate().toString(Qt::ISODate));
795                 bReadyToInstall = updateDialog->updateReadyToInstall();
796         }
797
798         LAMEXP_DELETE(updateDialog);
799         return bReadyToInstall;
800 }
801
802 /*
803  * Refresh list of favorites
804  */
805 void MainWindow::refreshFavorites(void)
806 {
807         QList<QAction*> folderList = m_outputFolderFavoritesMenu->actions();
808         QStringList favorites = m_settings->favoriteOutputFolders().split("|", QString::SkipEmptyParts);
809         while(favorites.count() > 6) favorites.removeFirst();
810
811         while(!folderList.isEmpty())
812         {
813                 QAction *currentItem = folderList.takeFirst();
814                 if(currentItem->isSeparator()) break;
815                 m_outputFolderFavoritesMenu->removeAction(currentItem);
816                 LAMEXP_DELETE(currentItem);
817         }
818
819         QAction *lastItem = m_outputFolderFavoritesMenu->actions().first();
820
821         while(!favorites.isEmpty())
822         {
823                 QString path = favorites.takeLast();
824                 if(QDir(path).exists())
825                 {
826                         QAction *action = new QAction(QIcon(":/icons/folder_go.png"), QDir::toNativeSeparators(path), this);
827                         action->setData(path);
828                         m_outputFolderFavoritesMenu->insertAction(lastItem, action);
829                         connect(action, SIGNAL(triggered(bool)), this, SLOT(gotoFavoriteFolder()));
830                         lastItem = action;
831                 }
832         }
833 }
834
835 /*
836  * Initilaize translation
837  */
838 void MainWindow::initializeTranslation(void)
839 {
840         bool translationLoaded = false;
841
842         //Try to load "external" translation file
843         if(!m_settings->currentLanguageFile().isEmpty())
844         {
845                 const QString qmFilePath = QFileInfo(m_settings->currentLanguageFile()).canonicalFilePath();
846                 if((!qmFilePath.isEmpty()) && QFileInfo(qmFilePath).exists() && QFileInfo(qmFilePath).isFile() && (QFileInfo(qmFilePath).suffix().compare("qm", Qt::CaseInsensitive) == 0))
847                 {
848                         if(lamexp_install_translator_from_file(qmFilePath))
849                         {
850                                 QList<QAction*> actions = m_languageActionGroup->actions();
851                                 while(!actions.isEmpty()) actions.takeFirst()->setChecked(false);
852                                 ui->actionLoadTranslationFromFile->setChecked(true);
853                                 translationLoaded = true;
854                         }
855                 }
856         }
857
858         //Try to load "built-in" translation file
859         if(!translationLoaded)
860         {
861                 QList<QAction*> languageActions = m_languageActionGroup->actions();
862                 while(!languageActions.isEmpty())
863                 {
864                         QAction *currentLanguage = languageActions.takeFirst();
865                         if(currentLanguage->data().toString().compare(m_settings->currentLanguage(), Qt::CaseInsensitive) == 0)
866                         {
867                                 currentLanguage->setChecked(true);
868                                 languageActionActivated(currentLanguage);
869                                 translationLoaded = true;
870                         }
871                 }
872         }
873
874         //Fallback to default translation
875         if(!translationLoaded)
876         {
877                 QList<QAction*> languageActions = m_languageActionGroup->actions();
878                 while(!languageActions.isEmpty())
879                 {
880                         QAction *currentLanguage = languageActions.takeFirst();
881                         if(currentLanguage->data().toString().compare(LAMEXP_DEFAULT_LANGID, Qt::CaseInsensitive) == 0)
882                         {
883                                 currentLanguage->setChecked(true);
884                                 languageActionActivated(currentLanguage);
885                                 translationLoaded = true;
886                         }
887                 }
888         }
889
890         //Make sure we loaded some translation
891         if(!translationLoaded)
892         {
893                 qFatal("Failed to load any translation, this is NOT supposed to happen!");
894         }
895 }
896
897 ////////////////////////////////////////////////////////////
898 // EVENTS
899 ////////////////////////////////////////////////////////////
900
901 /*
902  * Window is about to be shown
903  */
904 void MainWindow::showEvent(QShowEvent *event)
905 {
906         m_accepted = false;
907         m_dropNoteLabel->setGeometry(0, 0, ui->sourceFileView->width(), ui->sourceFileView->height());
908         sourceModelChanged();
909         
910         if(!event->spontaneous())
911         {
912                 ui->tabWidget->setCurrentIndex(0);
913         }
914
915         if(m_firstTimeShown)
916         {
917                 m_firstTimeShown = false;
918                 QTimer::singleShot(0, this, SLOT(windowShown()));
919         }
920         else
921         {
922                 if(m_settings->dropBoxWidgetEnabled())
923                 {
924                         m_dropBox->setVisible(true);
925                 }
926         }
927 }
928
929 /*
930  * Re-translate the UI
931  */
932 void MainWindow::changeEvent(QEvent *e)
933 {
934         if(e->type() == QEvent::LanguageChange)
935         {
936                 int comboBoxIndex[8];
937                 
938                 //Backup combobox indices, as retranslateUi() resets
939                 comboBoxIndex[0] = ui->comboBoxMP3ChannelMode->currentIndex();
940                 comboBoxIndex[1] = ui->comboBoxSamplingRate->currentIndex();
941                 comboBoxIndex[2] = ui->comboBoxAACProfile->currentIndex();
942                 comboBoxIndex[3] = ui->comboBoxAftenCodingMode->currentIndex();
943                 comboBoxIndex[4] = ui->comboBoxAftenDRCMode->currentIndex();
944                 comboBoxIndex[5] = ui->comboBoxNormalizationMode->currentIndex();
945                 comboBoxIndex[6] = 0; //comboBoxOpusOptimize->currentIndex();
946                 comboBoxIndex[7] = ui->comboBoxOpusFramesize->currentIndex();
947                 
948                 //Re-translate from UIC
949                 ui->retranslateUi(this);
950
951                 //Restore combobox indices
952                 ui->comboBoxMP3ChannelMode->setCurrentIndex(comboBoxIndex[0]);
953                 ui->comboBoxSamplingRate->setCurrentIndex(comboBoxIndex[1]);
954                 ui->comboBoxAACProfile->setCurrentIndex(comboBoxIndex[2]);
955                 ui->comboBoxAftenCodingMode->setCurrentIndex(comboBoxIndex[3]);
956                 ui->comboBoxAftenDRCMode->setCurrentIndex(comboBoxIndex[4]);
957                 ui->comboBoxNormalizationMode->setCurrentIndex(comboBoxIndex[5]);
958                 //comboBoxOpusOptimize->setCurrentIndex(comboBoxIndex[6]);
959                 ui->comboBoxOpusFramesize->setCurrentIndex(comboBoxIndex[7]);
960
961                 //Update the window title
962                 if(LAMEXP_DEBUG)
963                 {
964                         setWindowTitle(QString("%1 [!!! DEBUG BUILD !!!]").arg(windowTitle()));
965                 }
966                 else if(lamexp_version_demo())
967                 {
968                         setWindowTitle(QString("%1 [%2]").arg(windowTitle(), tr("DEMO VERSION")));
969                 }
970
971                 //Manually re-translate widgets that UIC doesn't handle
972                 m_dropNoteLabel->setText(QString("» %1 Â«").arg(tr("You can drop in audio files here!")));
973                 m_outputFolderNoteBox->setText(tr("Initializing directory outline, please be patient..."));
974                 m_showDetailsContextAction->setText(tr("Show Details"));
975                 m_previewContextAction->setText(tr("Open File in External Application"));
976                 m_findFileContextAction->setText(tr("Browse File Location"));
977                 m_showFolderContextAction->setText(tr("Browse Selected Folder"));
978                 m_refreshFolderContextAction->setText(tr("Refresh Directory Outline"));
979                 m_addFavoriteFolderAction->setText(tr("Bookmark Current Output Folder"));
980                 m_exportCsvContextAction->setText(tr("Export Meta Tags to CSV File"));
981                 m_importCsvContextAction->setText(tr("Import Meta Tags from CSV File"));
982
983                 //Force GUI update
984                 m_metaInfoModel->clearData();
985                 m_metaInfoModel->setData(m_metaInfoModel->index(4, 1), m_settings->metaInfoPosition());
986                 updateEncoder(m_settings->compressionEncoder());
987                 updateLameAlgoQuality(ui->sliderLameAlgoQuality->value());
988                 updateMaximumInstances(ui->sliderMaxInstances->value());
989                 renameOutputPatternChanged(ui->lineEditRenamePattern->text());
990
991                 //Re-install shell integration
992                 if(m_settings->shellIntegrationEnabled())
993                 {
994                         ShellIntegration::install();
995                 }
996
997                 //Translate system menu
998                 if(HMENU hMenu = ::GetSystemMenu(winId(), FALSE))
999                 {
1000                         ModifyMenu(hMenu, IDM_ABOUTBOX, MF_STRING | MF_BYCOMMAND, IDM_ABOUTBOX, QWCHAR(ui->buttonAbout->text()));
1001                 }
1002                         
1003                 //Force resize, if needed
1004                 tabPageChanged(ui->tabWidget->currentIndex());
1005         }
1006 }
1007
1008 /*
1009  * File dragged over window
1010  */
1011 void MainWindow::dragEnterEvent(QDragEnterEvent *event)
1012 {
1013         QStringList formats = event->mimeData()->formats();
1014         
1015         if(formats.contains("application/x-qt-windows-mime;value=\"FileNameW\"", Qt::CaseInsensitive) && formats.contains("text/uri-list", Qt::CaseInsensitive))
1016         {
1017                 event->acceptProposedAction();
1018         }
1019 }
1020
1021 /*
1022  * File dropped onto window
1023  */
1024 void MainWindow::dropEvent(QDropEvent *event)
1025 {
1026         ABORT_IF_BUSY;
1027
1028         QStringList droppedFiles;
1029         QList<QUrl> urls = event->mimeData()->urls();
1030
1031         while(!urls.isEmpty())
1032         {
1033                 QUrl currentUrl = urls.takeFirst();
1034                 QFileInfo file(currentUrl.toLocalFile());
1035                 if(!file.exists())
1036                 {
1037                         continue;
1038                 }
1039                 if(file.isFile())
1040                 {
1041                         qDebug("Dropped File: %s", file.canonicalFilePath().toUtf8().constData());
1042                         droppedFiles << file.canonicalFilePath();
1043                         continue;
1044                 }
1045                 if(file.isDir())
1046                 {
1047                         qDebug("Dropped Folder: %s", file.canonicalFilePath().toUtf8().constData());
1048                         QList<QFileInfo> list = QDir(file.canonicalFilePath()).entryInfoList(QDir::Files | QDir::NoSymLinks);
1049                         if(list.count() > 0)
1050                         {
1051                                 for(int j = 0; j < list.count(); j++)
1052                                 {
1053                                         droppedFiles << list.at(j).canonicalFilePath();
1054                                 }
1055                         }
1056                         else
1057                         {
1058                                 list = QDir(file.canonicalFilePath()).entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks);
1059                                 for(int j = 0; j < list.count(); j++)
1060                                 {
1061                                         qDebug("Descending to Folder: %s", list.at(j).canonicalFilePath().toUtf8().constData());
1062                                         urls.prepend(QUrl::fromLocalFile(list.at(j).canonicalFilePath()));
1063                                 }
1064                         }
1065                 }
1066         }
1067         
1068         if(!droppedFiles.isEmpty())
1069         {
1070                 addFilesDelayed(droppedFiles, true);
1071         }
1072 }
1073
1074 /*
1075  * Window tries to close
1076  */
1077 void MainWindow::closeEvent(QCloseEvent *event)
1078 {
1079         if(m_banner->isVisible() || m_delayedFileTimer->isActive())
1080         {
1081                 MessageBeep(MB_ICONEXCLAMATION);
1082                 event->ignore();
1083         }
1084         
1085         if(m_dropBox)
1086         {
1087                 m_dropBox->hide();
1088         }
1089 }
1090
1091 /*
1092  * Window was resized
1093  */
1094 void MainWindow::resizeEvent(QResizeEvent *event)
1095 {
1096         if(event) QMainWindow::resizeEvent(event);
1097         m_dropNoteLabel->setGeometry(0, 0, ui->sourceFileView->width(), ui->sourceFileView->height());
1098
1099         if(QWidget *port = ui->outputFolderView->viewport())
1100         {
1101                 m_outputFolderNoteBox->setGeometry(16, (port->height() - 64) / 2, port->width() - 32,  64);
1102         }
1103 }
1104
1105 /*
1106  * Key press event filter
1107  */
1108 void MainWindow::keyPressEvent(QKeyEvent *e)
1109 {
1110         if(e->key() == Qt::Key_Delete)
1111         {
1112                 if(ui->sourceFileView->isVisible())
1113                 {
1114                         QTimer::singleShot(0, this, SLOT(removeFileButtonClicked()));
1115                         return;
1116                 }
1117         }
1118
1119         if(e->modifiers().testFlag(Qt::ControlModifier) && (e->key() == Qt::Key_F5))
1120         {
1121                 initializeTranslation();
1122                 MessageBeep(MB_ICONINFORMATION);
1123                 return;
1124         }
1125
1126         if(e->key() == Qt::Key_F5)
1127         {
1128                 if(ui->outputFolderView->isVisible())
1129                 {
1130                         QTimer::singleShot(0, this, SLOT(refreshFolderContextActionTriggered()));
1131                         return;
1132                 }
1133         }
1134
1135         QMainWindow::keyPressEvent(e);
1136 }
1137
1138 /*
1139  * Event filter
1140  */
1141 bool MainWindow::eventFilter(QObject *obj, QEvent *event)
1142 {
1143         if(obj == m_fileSystemModel)
1144         {
1145                 if(QApplication::overrideCursor() == NULL)
1146                 {
1147                         QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
1148                         QTimer::singleShot(250, this, SLOT(restoreCursor()));
1149                 }
1150         }
1151
1152         return QMainWindow::eventFilter(obj, event);
1153 }
1154
1155 bool MainWindow::event(QEvent *e)
1156 {
1157         switch(e->type())
1158         {
1159         case lamexp_event_queryendsession:
1160                 qWarning("System is shutting down, main window prepares to close...");
1161                 if(m_banner->isVisible()) m_banner->close();
1162                 if(m_delayedFileTimer->isActive()) m_delayedFileTimer->stop();
1163                 return true;
1164         case lamexp_event_endsession:
1165                 qWarning("System is shutting down, main window will close now...");
1166                 if(isVisible())
1167                 {
1168                         while(!close())
1169                         {
1170                                 QApplication::processEvents(QEventLoop::WaitForMoreEvents & QEventLoop::ExcludeUserInputEvents);
1171                         }
1172                 }
1173                 m_fileListModel->clearFiles();
1174                 return true;
1175         case QEvent::MouseButtonPress:
1176                 if(ui->outputFolderEdit->isVisible())
1177                 {
1178                         QTimer::singleShot(0, this, SLOT(outputFolderEditFinished()));
1179                 }
1180         default:
1181                 return QMainWindow::event(e);
1182         }
1183 }
1184
1185 bool MainWindow::winEvent(MSG *message, long *result)
1186 {
1187         if((message->message == WM_SYSCOMMAND) && ((message->wParam & 0xFFF0) == IDM_ABOUTBOX))
1188         {
1189                 QTimer::singleShot(0, ui->buttonAbout, SLOT(click()));
1190                 *result = 0;
1191                 return true;
1192         }
1193         return WinSevenTaskbar::handleWinEvent(message, result);
1194 }
1195
1196 ////////////////////////////////////////////////////////////
1197 // Slots
1198 ////////////////////////////////////////////////////////////
1199
1200 // =========================================================
1201 // Show window slots
1202 // =========================================================
1203
1204 /*
1205  * Window shown
1206  */
1207 void MainWindow::windowShown(void)
1208 {
1209         const QStringList &arguments = lamexp_arguments(); //QApplication::arguments();
1210
1211         //First run?
1212         bool firstRun = false;
1213         for(int i = 0; i < arguments.count(); i++)
1214         {
1215                 /*QMessageBox::information(this, QString::number(i), arguments[i]);*/
1216                 if(!arguments[i].compare("--first-run", Qt::CaseInsensitive)) firstRun = true;
1217         }
1218
1219         //Check license
1220         if((m_settings->licenseAccepted() <= 0) || firstRun)
1221         {
1222                 int iAccepted = m_settings->licenseAccepted();
1223
1224                 if((iAccepted == 0) || firstRun)
1225                 {
1226                         AboutDialog *about = new AboutDialog(m_settings, this, true);
1227                         iAccepted = about->exec();
1228                         if(iAccepted <= 0) iAccepted = -2;
1229                         LAMEXP_DELETE(about);
1230                 }
1231
1232                 if(iAccepted <= 0)
1233                 {
1234                         m_settings->licenseAccepted(++iAccepted);
1235                         m_settings->syncNow();
1236                         QApplication::processEvents();
1237                         PlaySound(MAKEINTRESOURCE(IDR_WAVE_WHAMMY), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
1238                         QMessageBox::critical(this, tr("License Declined"), tr("You have declined the license. Consequently the application will exit now!"), tr("Goodbye!"));
1239                         QFileInfo uninstallerInfo = QFileInfo(QString("%1/Uninstall.exe").arg(QApplication::applicationDirPath()));
1240                         if(uninstallerInfo.exists())
1241                         {
1242                                 QString uninstallerDir = uninstallerInfo.canonicalPath();
1243                                 QString uninstallerPath = uninstallerInfo.canonicalFilePath();
1244                                 for(int i = 0; i < 3; i++)
1245                                 {
1246                                         HINSTANCE res = ShellExecuteW(reinterpret_cast<HWND>(this->winId()), L"open", QWCHAR(QDir::toNativeSeparators(uninstallerPath)), L"/Force", QWCHAR(QDir::toNativeSeparators(uninstallerDir)), SW_SHOWNORMAL);
1247                                         if(reinterpret_cast<int>(res) > 32) break;
1248                                 }
1249                         }
1250                         QApplication::quit();
1251                         return;
1252                 }
1253                 
1254                 PlaySound(MAKEINTRESOURCE(IDR_WAVE_WOOHOO), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
1255                 m_settings->licenseAccepted(1);
1256                 m_settings->syncNow();
1257                 if(lamexp_version_demo()) showAnnounceBox();
1258         }
1259         
1260         //Check for expiration
1261         if(lamexp_version_demo())
1262         {
1263                 if(QDate::currentDate() >= lamexp_version_expires())
1264                 {
1265                         qWarning("Binary has expired !!!");
1266                         PlaySound(MAKEINTRESOURCE(IDR_WAVE_WHAMMY), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
1267                         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)
1268                         {
1269                                 checkForUpdates();
1270                         }
1271                         QApplication::quit();
1272                         return;
1273                 }
1274         }
1275
1276         //Slow startup indicator
1277         if(m_settings->slowStartup() && m_settings->antivirNotificationsEnabled())
1278         {
1279                 QString message;
1280                 message += NOBR(tr("It seems that a bogus anti-virus software is slowing down the startup of LameXP.")).append("<br>");
1281                 message += NOBR(tr("Please refer to the %1 document for details and solutions!")).arg("<a href=\"http://lamexp.sourceforge.net/doc/FAQ.html#df406578\">F.A.Q.</a>").append("<br>");
1282                 if(QMessageBox::warning(this, tr("Slow Startup"), message, tr("Discard"), tr("Don't Show Again")) == 1)
1283                 {
1284                         m_settings->antivirNotificationsEnabled(false);
1285                         ui->actionDisableSlowStartupNotifications->setChecked(!m_settings->antivirNotificationsEnabled());
1286                 }
1287         }
1288
1289         //Update reminder
1290         if(QDate::currentDate() >= lamexp_version_date().addYears(1))
1291         {
1292                 qWarning("Binary is more than a year old, time to update!");
1293                 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"));
1294                 switch(ret)
1295                 {
1296                 case 0:
1297                         if(checkForUpdates())
1298                         {
1299                                 QApplication::quit();
1300                                 return;
1301                         }
1302                         break;
1303                 case 1:
1304                         QApplication::quit();
1305                         return;
1306                 default:
1307                         QEventLoop loop; QTimer::singleShot(7000, &loop, SLOT(quit()));
1308                         PlaySound(MAKEINTRESOURCE(IDR_WAVE_WAITING), GetModuleHandle(NULL), SND_RESOURCE | SND_ASYNC);
1309                         m_banner->show(tr("Skipping update check this time, please be patient..."), &loop);
1310                         break;
1311                 }
1312         }
1313         else if(m_settings->autoUpdateEnabled())
1314         {
1315                 QDate lastUpdateCheck = QDate::fromString(m_settings->autoUpdateLastCheck(), Qt::ISODate);
1316                 if(!firstRun && (!lastUpdateCheck.isValid() || QDate::currentDate() >= lastUpdateCheck.addDays(14)))
1317                 {
1318                         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)
1319                         {
1320                                 if(checkForUpdates())
1321                                 {
1322                                         QApplication::quit();
1323                                         return;
1324                                 }
1325                         }
1326                 }
1327         }
1328
1329         //Check for AAC support
1330         if(m_neroEncoderAvailable)
1331         {
1332                 if(m_settings->neroAacNotificationsEnabled())
1333                 {
1334                         if(lamexp_tool_version("neroAacEnc.exe") < lamexp_toolver_neroaac())
1335                         {
1336                                 QString messageText;
1337                                 messageText += NOBR(tr("LameXP detected that your version of the Nero AAC encoder is outdated!")).append("<br>");
1338                                 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>");
1339                                 messageText += NOBR(tr("You can download the latest version of the Nero AAC encoder from the Nero website at:")).append("<br>");
1340                                 messageText += "<nobr><tt>" + LINK(AboutDialog::neroAacUrl) + "</tt></nobr><br><br>";
1341                                 messageText += NOBR(tr("(Hint: Please ignore the name of the downloaded ZIP file and check the included 'changelog.txt' instead!)")).append("<br>");
1342                                 QMessageBox::information(this, tr("AAC Encoder Outdated"), messageText);
1343                         }
1344                 }
1345         }
1346         else
1347         {
1348                 if(m_settings->neroAacNotificationsEnabled() && (!(m_fhgEncoderAvailable || m_qaacEncoderAvailable)))
1349                 {
1350                         QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
1351                         if(appPath.isEmpty()) appPath = QCoreApplication::applicationDirPath();
1352                         QString messageText;
1353                         messageText += NOBR(tr("The Nero AAC encoder could not be found. AAC encoding support will be disabled.")).append("<br>");
1354                         messageText += NOBR(tr("Please put 'neroAacEnc.exe', 'neroAacDec.exe' and 'neroAacTag.exe' into the LameXP directory!")).append("<br><br>");
1355                         messageText += NOBR(tr("Your LameXP directory is located here:")).append("<br>");
1356                         messageText += QString("<nobr><tt>%1</tt></nobr><br><br>").arg(FSLINK(QDir::toNativeSeparators(appPath)));
1357                         messageText += NOBR(tr("You can download the Nero AAC encoder for free from the official Nero website at:")).append("<br>");
1358                         messageText += "<nobr><tt>" + LINK(AboutDialog::neroAacUrl) + "</tt></nobr><br>";
1359                         if(QMessageBox::information(this, tr("AAC Support Disabled"), messageText, tr("Discard"), tr("Don't Show Again")) == 1)
1360                         {
1361                                 m_settings->neroAacNotificationsEnabled(false);
1362                                 ui->actionDisableNeroAacNotifications->setChecked(!m_settings->neroAacNotificationsEnabled());
1363                         }
1364                 }
1365         }
1366
1367         //Add files from the command-line
1368         for(int i = 0; i < arguments.count() - 1; i++)
1369         {
1370                 QStringList addedFiles;
1371                 if(!arguments[i].compare("--add", Qt::CaseInsensitive))
1372                 {
1373                         QFileInfo currentFile(arguments[++i].trimmed());
1374                         qDebug("Adding file from CLI: %s", currentFile.absoluteFilePath().toUtf8().constData());
1375                         addedFiles.append(currentFile.absoluteFilePath());
1376                 }
1377                 if(!addedFiles.isEmpty())
1378                 {
1379                         addFilesDelayed(addedFiles);
1380                 }
1381         }
1382
1383         //Add folders from the command-line
1384         for(int i = 0; i < arguments.count() - 1; i++)
1385         {
1386                 if(!arguments[i].compare("--add-folder", Qt::CaseInsensitive))
1387                 {
1388                         QFileInfo currentFile(arguments[++i].trimmed());
1389                         qDebug("Adding folder from CLI: %s", currentFile.absoluteFilePath().toUtf8().constData());
1390                         addFolder(currentFile.absoluteFilePath(), false, true);
1391                 }
1392                 if(!arguments[i].compare("--add-recursive", Qt::CaseInsensitive))
1393                 {
1394                         QFileInfo currentFile(arguments[++i].trimmed());
1395                         qDebug("Adding folder recursively from CLI: %s", currentFile.absoluteFilePath().toUtf8().constData());
1396                         addFolder(currentFile.absoluteFilePath(), true, true);
1397                 }
1398         }
1399
1400         //Enable shell integration
1401         if(m_settings->shellIntegrationEnabled())
1402         {
1403                 ShellIntegration::install();
1404         }
1405
1406         //Make DropBox visible
1407         if(m_settings->dropBoxWidgetEnabled())
1408         {
1409                 m_dropBox->setVisible(true);
1410         }
1411 }
1412
1413 /*
1414  * Show announce box
1415  */
1416 void MainWindow::showAnnounceBox(void)
1417 {
1418         const unsigned int timeout = 8U;
1419
1420         const QString announceText = QString("%1<br><br>%2<br><nobr><tt>%3</tt></nobr><br>").arg
1421         (
1422                 NOBR("We are still looking for LameXP translators!"),
1423                 NOBR("If you are willing to translate LameXP to your language or to complete an existing translation, please refer to:"),
1424                 LINK("http://lamexp.sourceforge.net/doc/Translate.html")
1425         );
1426
1427         QMessageBox *announceBox = new QMessageBox(QMessageBox::Warning, "We want you!", announceText, QMessageBox::NoButton, this);
1428         announceBox->setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
1429         announceBox->setIconPixmap(QIcon(":/images/Announcement.png").pixmap(64,79));
1430         
1431         QTimer *timers[timeout+1];
1432         QPushButton *buttons[timeout+1];
1433
1434         for(unsigned int i = 0; i <= timeout; i++)
1435         {
1436                 QString text = (i > 0) ? QString("%1 (%2)").arg(tr("Discard"), QString::number(i)) : tr("Discard");
1437                 buttons[i] = announceBox->addButton(text, (i > 0) ? QMessageBox::NoRole : QMessageBox::AcceptRole);
1438         }
1439
1440         for(unsigned int i = 0; i <= timeout; i++)
1441         {
1442                 buttons[i]->setEnabled(i == 0);
1443                 buttons[i]->setVisible(i == timeout);
1444         }
1445
1446         for(unsigned int i = 0; i < timeout; i++)
1447         {
1448                 timers[i] = new QTimer(this);
1449                 timers[i]->setSingleShot(true);
1450                 timers[i]->setInterval(1000);
1451                 connect(timers[i], SIGNAL(timeout()), buttons[i+1], SLOT(hide()));
1452                 connect(timers[i], SIGNAL(timeout()), buttons[i], SLOT(show()));
1453                 if(i > 0)
1454                 {
1455                         connect(timers[i], SIGNAL(timeout()), timers[i-1], SLOT(start()));
1456                 }
1457         }
1458
1459         timers[timeout-1]->start();
1460         announceBox->exec();
1461
1462         for(unsigned int i = 0; i < timeout; i++)
1463         {
1464                 timers[i]->stop();
1465                 LAMEXP_DELETE(timers[i]);
1466         }
1467
1468         LAMEXP_DELETE(announceBox);
1469 }
1470
1471 // =========================================================
1472 // Main button solots
1473 // =========================================================
1474
1475 /*
1476  * Encode button
1477  */
1478 void MainWindow::encodeButtonClicked(void)
1479 {
1480         static const unsigned __int64 oneGigabyte = 1073741824ui64; 
1481         static const unsigned __int64 minimumFreeDiskspaceMultiplier = 2ui64;
1482         static const char *writeTestBuffer = "LAMEXP_WRITE_TEST";
1483         
1484         ABORT_IF_BUSY;
1485
1486         if(m_fileListModel->rowCount() < 1)
1487         {
1488                 QMessageBox::warning(this, tr("LameXP"), NOBR(tr("You must add at least one file to the list before proceeding!")));
1489                 ui->tabWidget->setCurrentIndex(0);
1490                 return;
1491         }
1492         
1493         QString tempFolder = m_settings->customTempPathEnabled() ? m_settings->customTempPath() : lamexp_temp_folder2();
1494         if(!QFileInfo(tempFolder).exists() || !QFileInfo(tempFolder).isDir())
1495         {
1496                 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)
1497                 {
1498                         SET_CHECKBOX_STATE(ui->checkBoxUseSystemTempFolder, m_settings->customTempPathEnabledDefault());
1499                 }
1500                 return;
1501         }
1502
1503         bool ok = false;
1504         unsigned __int64 currentFreeDiskspace = lamexp_free_diskspace(tempFolder, &ok);
1505
1506         if(ok && (currentFreeDiskspace < (oneGigabyte * minimumFreeDiskspaceMultiplier)))
1507         {
1508                 QStringList tempFolderParts = tempFolder.split("/", QString::SkipEmptyParts, Qt::CaseInsensitive);
1509                 tempFolderParts.takeLast();
1510                 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_WHAMMY), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
1511                 QString lowDiskspaceMsg = QString("%1<br>%2<br><br>%3<br>%4<br>").arg
1512                 (
1513                         NOBR(tr("There are less than %1 GB of free diskspace available on your system's TEMP folder.").arg(QString::number(minimumFreeDiskspaceMultiplier))),
1514                         NOBR(tr("It is highly recommend to free up more diskspace before proceeding with the encode!")),
1515                         NOBR(tr("Your TEMP folder is located at:")),
1516                         QString("<nobr><tt>%1</tt></nobr>").arg(FSLINK(tempFolderParts.join("\\")))
1517                 );
1518                 switch(QMessageBox::warning(this, tr("Low Diskspace Warning"), lowDiskspaceMsg, tr("Abort Encoding Process"), tr("Clean Disk Now"), tr("Ignore")))
1519                 {
1520                 case 1:
1521                         QProcess::startDetached(QString("%1/cleanmgr.exe").arg(lamexp_known_folder(lamexp_folder_systemfolder)), QStringList() << "/D" << tempFolderParts.first());
1522                 case 0:
1523                         return;
1524                         break;
1525                 default:
1526                         QMessageBox::warning(this, tr("Low Diskspace"), NOBR(tr("You are proceeding with low diskspace. Problems might occur!")));
1527                         break;
1528                 }
1529         }
1530
1531         switch(m_settings->compressionEncoder())
1532         {
1533         case SettingsModel::MP3Encoder:
1534         case SettingsModel::VorbisEncoder:
1535         case SettingsModel::AACEncoder:
1536         case SettingsModel::AC3Encoder:
1537         case SettingsModel::FLACEncoder:
1538         case SettingsModel::OpusEncoder:
1539         case SettingsModel::DCAEncoder:
1540         case SettingsModel::PCMEncoder:
1541                 break;
1542         default:
1543                 QMessageBox::warning(this, tr("LameXP"), tr("Sorry, an unsupported encoder has been chosen!"));
1544                 ui->tabWidget->setCurrentIndex(3);
1545                 return;
1546         }
1547
1548         if(!m_settings->outputToSourceDir())
1549         {
1550                 QFile writeTest(QString("%1/~%2.txt").arg(m_settings->outputDir(), lamexp_rand_str()));
1551                 if(!(writeTest.open(QIODevice::ReadWrite) && (writeTest.write(writeTestBuffer) == strlen(writeTestBuffer))))
1552                 {
1553                         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!")));
1554                         ui->tabWidget->setCurrentIndex(1);
1555                         return;
1556                 }
1557                 else
1558                 {
1559                         writeTest.close();
1560                         writeTest.remove();
1561                 }
1562         }
1563                 
1564         m_accepted = true;
1565         close();
1566 }
1567
1568 /*
1569  * About button
1570  */
1571 void MainWindow::aboutButtonClicked(void)
1572 {
1573         ABORT_IF_BUSY;
1574
1575         TEMP_HIDE_DROPBOX
1576         (
1577                 AboutDialog *aboutBox = new AboutDialog(m_settings, this);
1578                 aboutBox->exec();
1579                 LAMEXP_DELETE(aboutBox);
1580         );
1581 }
1582
1583 /*
1584  * Close button
1585  */
1586 void MainWindow::closeButtonClicked(void)
1587 {
1588         ABORT_IF_BUSY;
1589         close();
1590 }
1591
1592 // =========================================================
1593 // Tab widget slots
1594 // =========================================================
1595
1596 /*
1597  * Tab page changed
1598  */
1599 void MainWindow::tabPageChanged(int idx)
1600 {
1601         resizeEvent(NULL);
1602         
1603         QList<QAction*> actions = m_tabActionGroup->actions();
1604         for(int i = 0; i < actions.count(); i++)
1605         {
1606                 bool ok = false;
1607                 int actionIndex = actions.at(i)->data().toInt(&ok);
1608                 if(ok && actionIndex == idx)
1609                 {
1610                         actions.at(i)->setChecked(true);
1611                 }
1612         }
1613
1614         int initialWidth = this->width();
1615         int maximumWidth = QApplication::desktop()->availableGeometry().width();
1616
1617         //Make sure all tab headers are fully visible
1618         if(this->isVisible())
1619         {
1620                 int delta = ui->tabWidget->sizeHint().width() - ui->tabWidget->width();
1621                 if(delta > 0)
1622                 {
1623                         this->resize(qMin(this->width() + delta, maximumWidth), this->height());
1624                 }
1625         }
1626
1627         //Tab specific operations
1628         if(idx == ui->tabWidget->indexOf(ui->tabOptions) && ui->scrollArea->widget() && this->isVisible())
1629         {
1630                 ui->scrollArea->widget()->updateGeometry();
1631                 ui->scrollArea->viewport()->updateGeometry();
1632                 qApp->processEvents();
1633                 int delta = ui->scrollArea->widget()->width() - ui->scrollArea->viewport()->width();
1634                 if(delta > 0)
1635                 {
1636                         this->resize(qMin(this->width() + delta, maximumWidth), this->height());
1637                 }
1638         }
1639         else if(idx == ui->tabWidget->indexOf(ui->tabSourceFiles))
1640         {
1641                 m_dropNoteLabel->setGeometry(0, 0, ui->sourceFileView->width(), ui->sourceFileView->height());
1642         }
1643         else if(idx == ui->tabWidget->indexOf(ui->tabOutputDir))
1644         {
1645                 if(!m_fileSystemModel)
1646                 {
1647                         QTimer::singleShot(125, this, SLOT(initOutputFolderModel()));
1648                 }
1649                 else
1650                 {
1651                         CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
1652                 }
1653         }
1654
1655         //Center window around previous position
1656         if(initialWidth < this->width())
1657         {
1658                 QPoint prevPos = this->pos();
1659                 int delta = (this->width() - initialWidth) >> 2;
1660                 move(prevPos.x() - delta, prevPos.y());
1661         }
1662 }
1663
1664 /*
1665  * Tab action triggered
1666  */
1667 void MainWindow::tabActionActivated(QAction *action)
1668 {
1669         if(action && action->data().isValid())
1670         {
1671                 bool ok = false;
1672                 int index = action->data().toInt(&ok);
1673                 if(ok)
1674                 {
1675                         ui->tabWidget->setCurrentIndex(index);
1676                 }
1677         }
1678 }
1679
1680 // =========================================================
1681 // View menu slots
1682 // =========================================================
1683
1684 /*
1685  * Style action triggered
1686  */
1687 void MainWindow::styleActionActivated(QAction *action)
1688 {
1689         //Change style setting
1690         if(action && action->data().isValid())
1691         {
1692                 bool ok = false;
1693                 int actionIndex = action->data().toInt(&ok);
1694                 if(ok)
1695                 {
1696                         m_settings->interfaceStyle(actionIndex);
1697                 }
1698         }
1699
1700         //Set up the new style
1701         switch(m_settings->interfaceStyle())
1702         {
1703         case 1:
1704                 if(ui->actionStyleCleanlooks->isEnabled())
1705                 {
1706                         ui->actionStyleCleanlooks->setChecked(true);
1707                         QApplication::setStyle(new QCleanlooksStyle());
1708                         break;
1709                 }
1710         case 2:
1711                 if(ui->actionStyleWindowsVista->isEnabled())
1712                 {
1713                         ui->actionStyleWindowsVista->setChecked(true);
1714                         QApplication::setStyle(new QWindowsVistaStyle());
1715                         break;
1716                 }
1717         case 3:
1718                 if(ui->actionStyleWindowsXP->isEnabled())
1719                 {
1720                         ui->actionStyleWindowsXP->setChecked(true);
1721                         QApplication::setStyle(new QWindowsXPStyle());
1722                         break;
1723                 }
1724         case 4:
1725                 if(ui->actionStyleWindowsClassic->isEnabled())
1726                 {
1727                         ui->actionStyleWindowsClassic->setChecked(true);
1728                         QApplication::setStyle(new QWindowsStyle());
1729                         break;
1730                 }
1731         default:
1732                 ui->actionStylePlastique->setChecked(true);
1733                 QApplication::setStyle(new QPlastiqueStyle());
1734                 break;
1735         }
1736
1737         //Force re-translate after style change
1738         if(QEvent *e = new QEvent(QEvent::LanguageChange))
1739         {
1740                 changeEvent(e);
1741                 LAMEXP_DELETE(e);
1742         }
1743 }
1744
1745 /*
1746  * Language action triggered
1747  */
1748 void MainWindow::languageActionActivated(QAction *action)
1749 {
1750         if(action->data().type() == QVariant::String)
1751         {
1752                 QString langId = action->data().toString();
1753
1754                 if(lamexp_install_translator(langId))
1755                 {
1756                         action->setChecked(true);
1757                         ui->actionLoadTranslationFromFile->setChecked(false);
1758                         m_settings->currentLanguage(langId);
1759                         m_settings->currentLanguageFile(QString());
1760                 }
1761         }
1762 }
1763
1764 /*
1765  * Load language from file action triggered
1766  */
1767 void MainWindow::languageFromFileActionActivated(bool checked)
1768 {
1769         QFileDialog dialog(this, tr("Load Translation"));
1770         dialog.setFileMode(QFileDialog::ExistingFile);
1771         dialog.setNameFilter(QString("%1 (*.qm)").arg(tr("Translation Files")));
1772
1773         if(dialog.exec())
1774         {
1775                 QStringList selectedFiles = dialog.selectedFiles();
1776                 const QString qmFile = QFileInfo(selectedFiles.first()).canonicalFilePath();
1777                 if(lamexp_install_translator_from_file(qmFile))
1778                 {
1779                         QList<QAction*> actions = m_languageActionGroup->actions();
1780                         while(!actions.isEmpty())
1781                         {
1782                                 actions.takeFirst()->setChecked(false);
1783                         }
1784                         ui->actionLoadTranslationFromFile->setChecked(true);
1785                         m_settings->currentLanguageFile(qmFile);
1786                 }
1787                 else
1788                 {
1789                         languageActionActivated(m_languageActionGroup->actions().first());
1790                 }
1791         }
1792 }
1793
1794 // =========================================================
1795 // Tools menu slots
1796 // =========================================================
1797
1798 /*
1799  * Disable update reminder action
1800  */
1801 void MainWindow::disableUpdateReminderActionTriggered(bool checked)
1802 {
1803         if(checked)
1804         {
1805                 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))
1806                 {
1807                         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!"))));
1808                         m_settings->autoUpdateEnabled(false);
1809                 }
1810                 else
1811                 {
1812                         m_settings->autoUpdateEnabled(true);
1813                 }
1814         }
1815         else
1816         {
1817                         QMessageBox::information(this, tr("Update Reminder"), NOBR(tr("The update reminder has been re-enabled.")));
1818                         m_settings->autoUpdateEnabled(true);
1819         }
1820
1821         ui->actionDisableUpdateReminder->setChecked(!m_settings->autoUpdateEnabled());
1822 }
1823
1824 /*
1825  * Disable sound effects action
1826  */
1827 void MainWindow::disableSoundsActionTriggered(bool checked)
1828 {
1829         if(checked)
1830         {
1831                 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))
1832                 {
1833                         QMessageBox::information(this, tr("Sound Effects"), NOBR(tr("All sound effects have been disabled.")));
1834                         m_settings->soundsEnabled(false);
1835                 }
1836                 else
1837                 {
1838                         m_settings->soundsEnabled(true);
1839                 }
1840         }
1841         else
1842         {
1843                         QMessageBox::information(this, tr("Sound Effects"), NOBR(tr("The sound effects have been re-enabled.")));
1844                         m_settings->soundsEnabled(true);
1845         }
1846
1847         ui->actionDisableSounds->setChecked(!m_settings->soundsEnabled());
1848 }
1849
1850 /*
1851  * Disable Nero AAC encoder action
1852  */
1853 void MainWindow::disableNeroAacNotificationsActionTriggered(bool checked)
1854 {
1855         if(checked)
1856         {
1857                 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))
1858                 {
1859                         QMessageBox::information(this, tr("Nero AAC Notifications"), NOBR(tr("All Nero AAC Encoder notifications have been disabled.")));
1860                         m_settings->neroAacNotificationsEnabled(false);
1861                 }
1862                 else
1863                 {
1864                         m_settings->neroAacNotificationsEnabled(true);
1865                 }
1866         }
1867         else
1868         {
1869                         QMessageBox::information(this, tr("Nero AAC Notifications"), NOBR(tr("The Nero AAC Encoder notifications have been re-enabled.")));
1870                         m_settings->neroAacNotificationsEnabled(true);
1871         }
1872
1873         ui->actionDisableNeroAacNotifications->setChecked(!m_settings->neroAacNotificationsEnabled());
1874 }
1875
1876 /*
1877  * Disable slow startup action
1878  */
1879 void MainWindow::disableSlowStartupNotificationsActionTriggered(bool checked)
1880 {
1881         if(checked)
1882         {
1883                 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))
1884                 {
1885                         QMessageBox::information(this, tr("Slow Startup Notifications"), NOBR(tr("The slow startup notifications have been disabled.")));
1886                         m_settings->antivirNotificationsEnabled(false);
1887                 }
1888                 else
1889                 {
1890                         m_settings->antivirNotificationsEnabled(true);
1891                 }
1892         }
1893         else
1894         {
1895                         QMessageBox::information(this, tr("Slow Startup Notifications"), NOBR(tr("The slow startup notifications have been re-enabled.")));
1896                         m_settings->antivirNotificationsEnabled(true);
1897         }
1898
1899         ui->actionDisableSlowStartupNotifications->setChecked(!m_settings->antivirNotificationsEnabled());
1900 }
1901
1902 /*
1903  * Import a Cue Sheet file
1904  */
1905 void MainWindow::importCueSheetActionTriggered(bool checked)
1906 {
1907         ABORT_IF_BUSY;
1908         
1909         TEMP_HIDE_DROPBOX
1910         (
1911                 while(true)
1912                 {
1913                         int result = 0;
1914                         QString selectedCueFile;
1915
1916                         if(USE_NATIVE_FILE_DIALOG)
1917                         {
1918                                 selectedCueFile = QFileDialog::getOpenFileName(this, tr("Open Cue Sheet"), m_settings->mostRecentInputPath(), QString("%1 (*.cue)").arg(tr("Cue Sheet File")));
1919                         }
1920                         else
1921                         {
1922                                 QFileDialog dialog(this, tr("Open Cue Sheet"));
1923                                 dialog.setFileMode(QFileDialog::ExistingFile);
1924                                 dialog.setNameFilter(QString("%1 (*.cue)").arg(tr("Cue Sheet File")));
1925                                 dialog.setDirectory(m_settings->mostRecentInputPath());
1926                                 if(dialog.exec())
1927                                 {
1928                                         selectedCueFile = dialog.selectedFiles().first();
1929                                 }
1930                         }
1931
1932                         if(!selectedCueFile.isEmpty())
1933                         {
1934                                 m_settings->mostRecentInputPath(QFileInfo(selectedCueFile).canonicalPath());
1935                                 CueImportDialog *cueImporter  = new CueImportDialog(this, m_fileListModel, selectedCueFile);
1936                                 result = cueImporter->exec();
1937                                 LAMEXP_DELETE(cueImporter);
1938                         }
1939
1940                         if(result != (-1)) break;
1941                 }
1942         );
1943 }
1944
1945 /*
1946  * Show the "drop box" widget
1947  */
1948 void MainWindow::showDropBoxWidgetActionTriggered(bool checked)
1949 {
1950         m_settings->dropBoxWidgetEnabled(true);
1951         
1952         if(!m_dropBox->isVisible())
1953         {
1954                 m_dropBox->show();
1955         }
1956         
1957         lamexp_blink_window(m_dropBox);
1958 }
1959
1960 /*
1961  * Check for beta (pre-release) updates
1962  */
1963 void MainWindow::checkForBetaUpdatesActionTriggered(bool checked)
1964 {       
1965         bool checkUpdatesNow = false;
1966         
1967         if(checked)
1968         {
1969                 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))
1970                 {
1971                         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")))
1972                         {
1973                                 checkUpdatesNow = true;
1974                         }
1975                         m_settings->autoUpdateCheckBeta(true);
1976                 }
1977                 else
1978                 {
1979                         m_settings->autoUpdateCheckBeta(false);
1980                 }
1981         }
1982         else
1983         {
1984                         QMessageBox::information(this, tr("Beta Updates"), NOBR(tr("LameXP will <i>not</i> check for Beta (pre-release) updates from now on.")));
1985                         m_settings->autoUpdateCheckBeta(false);
1986         }
1987
1988         ui->actionCheckForBetaUpdates->setChecked(m_settings->autoUpdateCheckBeta());
1989
1990         if(checkUpdatesNow)
1991         {
1992                 if(checkForUpdates())
1993                 {
1994                         QApplication::quit();
1995                 }
1996         }
1997 }
1998
1999 /*
2000  * Hibernate computer action
2001  */
2002 void MainWindow::hibernateComputerActionTriggered(bool checked)
2003 {
2004         if(checked)
2005         {
2006                 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))
2007                 {
2008                         QMessageBox::information(this, tr("Hibernate Computer"), NOBR(tr("LameXP will hibernate the computer on shutdown from now on.")));
2009                         m_settings->hibernateComputer(true);
2010                 }
2011                 else
2012                 {
2013                         m_settings->hibernateComputer(false);
2014                 }
2015         }
2016         else
2017         {
2018                         QMessageBox::information(this, tr("Hibernate Computer"), NOBR(tr("LameXP will <i>not</i> hibernate the computer on shutdown from now on.")));
2019                         m_settings->hibernateComputer(false);
2020         }
2021
2022         ui->actionHibernateComputer->setChecked(m_settings->hibernateComputer());
2023 }
2024
2025 /*
2026  * Disable shell integration action
2027  */
2028 void MainWindow::disableShellIntegrationActionTriggered(bool checked)
2029 {
2030         if(checked)
2031         {
2032                 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))
2033                 {
2034                         ShellIntegration::remove();
2035                         QMessageBox::information(this, tr("Shell Integration"), NOBR(tr("The LameXP shell integration has been disabled.")));
2036                         m_settings->shellIntegrationEnabled(false);
2037                 }
2038                 else
2039                 {
2040                         m_settings->shellIntegrationEnabled(true);
2041                 }
2042         }
2043         else
2044         {
2045                         ShellIntegration::install();
2046                         QMessageBox::information(this, tr("Shell Integration"), NOBR(tr("The LameXP shell integration has been re-enabled.")));
2047                         m_settings->shellIntegrationEnabled(true);
2048         }
2049
2050         ui->actionDisableShellIntegration->setChecked(!m_settings->shellIntegrationEnabled());
2051         
2052         if(lamexp_portable_mode() && ui->actionDisableShellIntegration->isChecked())
2053         {
2054                 ui->actionDisableShellIntegration->setEnabled(false);
2055         }
2056 }
2057
2058 // =========================================================
2059 // Help menu slots
2060 // =========================================================
2061
2062 /*
2063  * Visit homepage action
2064  */
2065 void MainWindow::visitHomepageActionActivated(void)
2066 {
2067         if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
2068         {
2069                 if(action->data().isValid() && (action->data().type() == QVariant::String))
2070                 {
2071                         QDesktopServices::openUrl(QUrl(action->data().toString()));
2072                 }
2073         }
2074 }
2075
2076 /*
2077  * Show document
2078  */
2079 void MainWindow::documentActionActivated(void)
2080 {
2081         if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
2082         {
2083                 if(action->data().isValid() && (action->data().type() == QVariant::String))
2084                 {
2085                         QFileInfo document(action->data().toString());
2086                         QFileInfo resource(QString(":/doc/%1.html").arg(document.baseName()));
2087                         if(document.exists() && document.isFile() && (document.size() == resource.size()))
2088                         {
2089                                 QDesktopServices::openUrl(QUrl::fromLocalFile(document.canonicalFilePath()));
2090                         }
2091                         else
2092                         {
2093                                 QFile source(resource.filePath());
2094                                 QFile output(QString("%1/%2.%3.html").arg(lamexp_temp_folder2(), document.baseName(), lamexp_rand_str().left(8)));
2095                                 if(source.open(QIODevice::ReadOnly) && output.open(QIODevice::ReadWrite))
2096                                 {
2097                                         output.write(source.readAll());
2098                                         action->setData(output.fileName());
2099                                         source.close();
2100                                         output.close();
2101                                         QDesktopServices::openUrl(QUrl::fromLocalFile(output.fileName()));
2102                                 }
2103                         }
2104                 }
2105         }
2106 }
2107
2108 /*
2109  * Check for updates action
2110  */
2111 void MainWindow::checkUpdatesActionActivated(void)
2112 {
2113         ABORT_IF_BUSY;
2114         bool bFlag = false;
2115
2116         TEMP_HIDE_DROPBOX
2117         (
2118                 bFlag = checkForUpdates();
2119         );
2120         
2121         if(bFlag)
2122         {
2123                 QApplication::quit();
2124         }
2125 }
2126
2127 // =========================================================
2128 // Source file slots
2129 // =========================================================
2130
2131 /*
2132  * Add file(s) button
2133  */
2134 void MainWindow::addFilesButtonClicked(void)
2135 {
2136         ABORT_IF_BUSY;
2137
2138         TEMP_HIDE_DROPBOX
2139         (
2140                 if(USE_NATIVE_FILE_DIALOG)
2141                 {
2142                         QStringList fileTypeFilters = DecoderRegistry::getSupportedTypes();
2143                         QStringList selectedFiles = QFileDialog::getOpenFileNames(this, tr("Add file(s)"), m_settings->mostRecentInputPath(), fileTypeFilters.join(";;"));
2144                         if(!selectedFiles.isEmpty())
2145                         {
2146                                 m_settings->mostRecentInputPath(QFileInfo(selectedFiles.first()).canonicalPath());
2147                                 addFiles(selectedFiles);
2148                         }
2149                 }
2150                 else
2151                 {
2152                         QFileDialog dialog(this, tr("Add file(s)"));
2153                         QStringList fileTypeFilters = DecoderRegistry::getSupportedTypes();
2154                         dialog.setFileMode(QFileDialog::ExistingFiles);
2155                         dialog.setNameFilter(fileTypeFilters.join(";;"));
2156                         dialog.setDirectory(m_settings->mostRecentInputPath());
2157                         if(dialog.exec())
2158                         {
2159                                 QStringList selectedFiles = dialog.selectedFiles();
2160                                 if(!selectedFiles.isEmpty())
2161                                 {
2162                                         m_settings->mostRecentInputPath(QFileInfo(selectedFiles.first()).canonicalPath());
2163                                         addFiles(selectedFiles);
2164                                 }
2165                         }
2166                 }
2167         );
2168 }
2169
2170 /*
2171  * Open folder action
2172  */
2173 void MainWindow::openFolderActionActivated(void)
2174 {
2175         ABORT_IF_BUSY;
2176         QString selectedFolder;
2177         
2178         if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
2179         {
2180                 TEMP_HIDE_DROPBOX
2181                 (
2182                         if(USE_NATIVE_FILE_DIALOG)
2183                         {
2184                                 selectedFolder = QFileDialog::getExistingDirectory(this, tr("Add Folder"), m_settings->mostRecentInputPath());
2185                         }
2186                         else
2187                         {
2188                                 QFileDialog dialog(this, tr("Add Folder"));
2189                                 dialog.setFileMode(QFileDialog::DirectoryOnly);
2190                                 dialog.setDirectory(m_settings->mostRecentInputPath());
2191                                 if(dialog.exec())
2192                                 {
2193                                         selectedFolder = dialog.selectedFiles().first();
2194                                 }
2195                         }
2196                         
2197                         if(!selectedFolder.isEmpty())
2198                         {
2199                                 m_settings->mostRecentInputPath(QDir(selectedFolder).canonicalPath());
2200                                 addFolder(selectedFolder, action->data().toBool());
2201                         }
2202                 );
2203         }
2204 }
2205
2206 /*
2207  * Remove file button
2208  */
2209 void MainWindow::removeFileButtonClicked(void)
2210 {
2211         if(ui->sourceFileView->currentIndex().isValid())
2212         {
2213                 int iRow = ui->sourceFileView->currentIndex().row();
2214                 m_fileListModel->removeFile(ui->sourceFileView->currentIndex());
2215                 ui->sourceFileView->selectRow(iRow < m_fileListModel->rowCount() ? iRow : m_fileListModel->rowCount()-1);
2216         }
2217 }
2218
2219 /*
2220  * Clear files button
2221  */
2222 void MainWindow::clearFilesButtonClicked(void)
2223 {
2224         m_fileListModel->clearFiles();
2225 }
2226
2227 /*
2228  * Move file up button
2229  */
2230 void MainWindow::fileUpButtonClicked(void)
2231 {
2232         if(ui->sourceFileView->currentIndex().isValid())
2233         {
2234                 int iRow = ui->sourceFileView->currentIndex().row() - 1;
2235                 m_fileListModel->moveFile(ui->sourceFileView->currentIndex(), -1);
2236                 ui->sourceFileView->selectRow(iRow >= 0 ? iRow : 0);
2237         }
2238 }
2239
2240 /*
2241  * Move file down button
2242  */
2243 void MainWindow::fileDownButtonClicked(void)
2244 {
2245         if(ui->sourceFileView->currentIndex().isValid())
2246         {
2247                 int iRow = ui->sourceFileView->currentIndex().row() + 1;
2248                 m_fileListModel->moveFile(ui->sourceFileView->currentIndex(), 1);
2249                 ui->sourceFileView->selectRow(iRow < m_fileListModel->rowCount() ? iRow : m_fileListModel->rowCount()-1);
2250         }
2251 }
2252
2253 /*
2254  * Show details button
2255  */
2256 void MainWindow::showDetailsButtonClicked(void)
2257 {
2258         ABORT_IF_BUSY;
2259
2260         int iResult = 0;
2261         MetaInfoDialog *metaInfoDialog = new MetaInfoDialog(this);
2262         QModelIndex index = ui->sourceFileView->currentIndex();
2263
2264         while(index.isValid())
2265         {
2266                 if(iResult > 0)
2267                 {
2268                         index = m_fileListModel->index(index.row() + 1, index.column()); 
2269                         ui->sourceFileView->selectRow(index.row());
2270                 }
2271                 if(iResult < 0)
2272                 {
2273                         index = m_fileListModel->index(index.row() - 1, index.column()); 
2274                         ui->sourceFileView->selectRow(index.row());
2275                 }
2276
2277                 AudioFileModel &file = (*m_fileListModel)[index];
2278                 TEMP_HIDE_DROPBOX
2279                 (
2280                         iResult = metaInfoDialog->exec(file, index.row() > 0, index.row() < m_fileListModel->rowCount() - 1);
2281                 );
2282                 
2283                 if(iResult == INT_MAX)
2284                 {
2285                         m_metaInfoModel->assignInfoFrom(file);
2286                         ui->tabWidget->setCurrentIndex(ui->tabWidget->indexOf(ui->tabMetaData));
2287                         break;
2288                 }
2289
2290                 if(!iResult) break;
2291         }
2292
2293         LAMEXP_DELETE(metaInfoDialog);
2294         QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
2295         sourceFilesScrollbarMoved(0);
2296 }
2297
2298 /*
2299  * Show context menu for source files
2300  */
2301 void MainWindow::sourceFilesContextMenu(const QPoint &pos)
2302 {
2303         QAbstractScrollArea *scrollArea = dynamic_cast<QAbstractScrollArea*>(QObject::sender());
2304         QWidget *sender = scrollArea ? scrollArea->viewport() : dynamic_cast<QWidget*>(QObject::sender());
2305
2306         if(sender)
2307         {
2308                 if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0)
2309                 {
2310                         m_sourceFilesContextMenu->popup(sender->mapToGlobal(pos));
2311                 }
2312         }
2313 }
2314
2315 /*
2316  * Scrollbar of source files moved
2317  */
2318 void MainWindow::sourceFilesScrollbarMoved(int)
2319 {
2320         ui->sourceFileView->resizeColumnToContents(0);
2321 }
2322
2323 /*
2324  * Open selected file in external player
2325  */
2326 void MainWindow::previewContextActionTriggered(void)
2327 {
2328         const static char *appNames[3] = {"smplayer_portable.exe", "smplayer.exe", "mplayer.exe"};
2329         const static wchar_t *registryKey = L"SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{DB9E4EAB-2717-499F-8D56-4CC8A644AB60}";
2330         
2331         QModelIndex index = ui->sourceFileView->currentIndex();
2332         if(!index.isValid())
2333         {
2334                 return;
2335         }
2336
2337         QString mplayerPath;
2338         HKEY registryKeyHandle;
2339
2340         if(RegOpenKeyExW(HKEY_LOCAL_MACHINE, registryKey, 0, KEY_READ, &registryKeyHandle) == ERROR_SUCCESS)
2341         {
2342                 wchar_t Buffer[4096];
2343                 DWORD BuffSize = sizeof(wchar_t*) * 4096;
2344                 if(RegQueryValueExW(registryKeyHandle, L"InstallLocation", 0, 0, reinterpret_cast<BYTE*>(Buffer), &BuffSize) == ERROR_SUCCESS)
2345                 {
2346                         mplayerPath = QString::fromUtf16(reinterpret_cast<const unsigned short*>(Buffer));
2347                 }
2348         }
2349
2350         if(!mplayerPath.isEmpty())
2351         {
2352                 QDir mplayerDir(mplayerPath);
2353                 if(mplayerDir.exists())
2354                 {
2355                         for(int i = 0; i < 3; i++)
2356                         {
2357                                 if(mplayerDir.exists(appNames[i]))
2358                                 {
2359                                         QProcess::startDetached(mplayerDir.absoluteFilePath(appNames[i]), QStringList() << QDir::toNativeSeparators(m_fileListModel->getFile(index).filePath()));
2360                                         return;
2361                                 }
2362                         }
2363                 }
2364         }
2365         
2366         QDesktopServices::openUrl(QString("file:///").append(m_fileListModel->getFile(index).filePath()));
2367 }
2368
2369 /*
2370  * Find selected file in explorer
2371  */
2372 void MainWindow::findFileContextActionTriggered(void)
2373 {
2374         QModelIndex index = ui->sourceFileView->currentIndex();
2375         if(index.isValid())
2376         {
2377                 QString systemRootPath;
2378
2379                 QDir systemRoot(lamexp_known_folder(lamexp_folder_systemfolder));
2380                 if(systemRoot.exists() && systemRoot.cdUp())
2381                 {
2382                         systemRootPath = systemRoot.canonicalPath();
2383                 }
2384
2385                 if(!systemRootPath.isEmpty())
2386                 {
2387                         QFileInfo explorer(QString("%1/explorer.exe").arg(systemRootPath));
2388                         if(explorer.exists() && explorer.isFile())
2389                         {
2390                                 QProcess::execute(explorer.canonicalFilePath(), QStringList() << "/select," << QDir::toNativeSeparators(m_fileListModel->getFile(index).filePath()));
2391                                 return;
2392                         }
2393                 }
2394                 else
2395                 {
2396                         qWarning("SystemRoot directory could not be detected!");
2397                 }
2398         }
2399 }
2400
2401 /*
2402  * Add all pending files
2403  */
2404 void MainWindow::handleDelayedFiles(void)
2405 {
2406         m_delayedFileTimer->stop();
2407
2408         if(m_delayedFileList->isEmpty())
2409         {
2410                 return;
2411         }
2412
2413         if(m_banner->isVisible())
2414         {
2415                 m_delayedFileTimer->start(5000);
2416                 return;
2417         }
2418
2419         QStringList selectedFiles;
2420         ui->tabWidget->setCurrentIndex(0);
2421
2422         while(!m_delayedFileList->isEmpty())
2423         {
2424                 QFileInfo currentFile = QFileInfo(m_delayedFileList->takeFirst());
2425                 if(!currentFile.exists() || !currentFile.isFile())
2426                 {
2427                         continue;
2428                 }
2429                 selectedFiles << currentFile.canonicalFilePath();
2430         }
2431         
2432         addFiles(selectedFiles);
2433 }
2434
2435 /*
2436  * Export Meta tags to CSV file
2437  */
2438 void MainWindow::exportCsvContextActionTriggered(void)
2439 {
2440         TEMP_HIDE_DROPBOX
2441         (
2442                 QString selectedCsvFile;
2443         
2444                 if(USE_NATIVE_FILE_DIALOG)
2445                 {
2446                         selectedCsvFile = QFileDialog::getSaveFileName(this, tr("Save CSV file"), m_settings->mostRecentInputPath(), QString("%1 (*.csv)").arg(tr("CSV File")));
2447                 }
2448                 else
2449                 {
2450                         QFileDialog dialog(this, tr("Save CSV file"));
2451                         dialog.setFileMode(QFileDialog::AnyFile);
2452                         dialog.setAcceptMode(QFileDialog::AcceptSave);
2453                         dialog.setNameFilter(QString("%1 (*.csv)").arg(tr("CSV File")));
2454                         dialog.setDirectory(m_settings->mostRecentInputPath());
2455                         if(dialog.exec())
2456                         {
2457                                 selectedCsvFile = dialog.selectedFiles().first();
2458                         }
2459                 }
2460
2461                 if(!selectedCsvFile.isEmpty())
2462                 {
2463                         m_settings->mostRecentInputPath(QFileInfo(selectedCsvFile).canonicalPath());
2464                         switch(m_fileListModel->exportToCsv(selectedCsvFile))
2465                         {
2466                         case FileListModel::CsvError_NoTags:
2467                                 QMessageBox::critical(this, tr("CSV Export"), NOBR(tr("Sorry, there are no meta tags that can be exported!")));
2468                                 break;
2469                         case FileListModel::CsvError_FileOpen:
2470                                 QMessageBox::critical(this, tr("CSV Export"), NOBR(tr("Sorry, failed to open CSV file for writing!")));
2471                                 break;
2472                         case FileListModel::CsvError_FileWrite:
2473                                 QMessageBox::critical(this, tr("CSV Export"), NOBR(tr("Sorry, failed to write to the CSV file!")));
2474                                 break;
2475                         case FileListModel::CsvError_OK:
2476                                 QMessageBox::information(this, tr("CSV Export"), NOBR(tr("The CSV files was created successfully!")));
2477                                 break;
2478                         default:
2479                                 qWarning("exportToCsv: Unknown return code!");
2480                         }
2481                 }
2482         );
2483 }
2484
2485
2486 /*
2487  * Import Meta tags from CSV file
2488  */
2489 void MainWindow::importCsvContextActionTriggered(void)
2490 {
2491         TEMP_HIDE_DROPBOX
2492         (
2493                 QString selectedCsvFile;
2494         
2495                 if(USE_NATIVE_FILE_DIALOG)
2496                 {
2497                         selectedCsvFile = QFileDialog::getOpenFileName(this, tr("Open CSV file"), m_settings->mostRecentInputPath(), QString("%1 (*.csv)").arg(tr("CSV File")));
2498                 }
2499                 else
2500                 {
2501                         QFileDialog dialog(this, tr("Open CSV file"));
2502                         dialog.setFileMode(QFileDialog::ExistingFile);
2503                         dialog.setNameFilter(QString("%1 (*.csv)").arg(tr("CSV File")));
2504                         dialog.setDirectory(m_settings->mostRecentInputPath());
2505                         if(dialog.exec())
2506                         {
2507                                 selectedCsvFile = dialog.selectedFiles().first();
2508                         }
2509                 }
2510
2511                 if(!selectedCsvFile.isEmpty())
2512                 {
2513                         m_settings->mostRecentInputPath(QFileInfo(selectedCsvFile).canonicalPath());
2514                         switch(m_fileListModel->importFromCsv(this, selectedCsvFile))
2515                         {
2516                         case FileListModel::CsvError_FileOpen:
2517                                 QMessageBox::critical(this, tr("CSV Import"), NOBR(tr("Sorry, failed to open CSV file for reading!")));
2518                                 break;
2519                         case FileListModel::CsvError_FileRead:
2520                                 QMessageBox::critical(this, tr("CSV Import"), NOBR(tr("Sorry, failed to read from the CSV file!")));
2521                                 break;
2522                         case FileListModel::CsvError_NoTags:
2523                                 QMessageBox::critical(this, tr("CSV Import"), NOBR(tr("Sorry, the CSV file does not contain any known fields!")));
2524                                 break;
2525                         case FileListModel::CsvError_Incomplete:
2526                                 QMessageBox::warning(this, tr("CSV Import"), NOBR(tr("CSV file is incomplete. Not all files were updated!")));
2527                                 break;
2528                         case FileListModel::CsvError_OK:
2529                                 QMessageBox::information(this, tr("CSV Import"), NOBR(tr("The CSV files was imported successfully!")));
2530                                 break;
2531                         case FileListModel::CsvError_Aborted:
2532                                 /* User aborted, ignore! */
2533                                 break;
2534                         default:
2535                                 qWarning("exportToCsv: Unknown return code!");
2536                         }
2537                 }
2538         );
2539 }
2540
2541 /*
2542  * Show or hide Drag'n'Drop notice after model reset
2543  */
2544 void MainWindow::sourceModelChanged(void)
2545 {
2546         m_dropNoteLabel->setVisible(m_fileListModel->rowCount() <= 0);
2547 }
2548
2549 // =========================================================
2550 // Output folder slots
2551 // =========================================================
2552
2553 /*
2554  * Output folder changed (mouse clicked)
2555  */
2556 void MainWindow::outputFolderViewClicked(const QModelIndex &index)
2557 {
2558         if(index.isValid() && (ui->outputFolderView->currentIndex() != index))
2559         {
2560                 ui->outputFolderView->setCurrentIndex(index);
2561         }
2562         
2563         if(m_fileSystemModel && index.isValid())
2564         {
2565                 QString selectedDir = m_fileSystemModel->filePath(index);
2566                 if(selectedDir.length() < 3) selectedDir.append(QDir::separator());
2567                 ui->outputFolderLabel->setText(QDir::toNativeSeparators(selectedDir));
2568                 m_settings->outputDir(selectedDir);
2569         }
2570         else
2571         {
2572                 ui->outputFolderLabel->setText(QDir::toNativeSeparators(m_settings->outputDir()));
2573         }
2574 }
2575
2576 /*
2577  * Output folder changed (mouse moved)
2578  */
2579 void MainWindow::outputFolderViewMoved(const QModelIndex &index)
2580 {
2581         if(QApplication::mouseButtons() & Qt::LeftButton)
2582         {
2583                 outputFolderViewClicked(index);
2584         }
2585 }
2586
2587 /*
2588  * Goto desktop button
2589  */
2590 void MainWindow::gotoDesktopButtonClicked(void)
2591 {
2592         if(!m_fileSystemModel)
2593         {
2594                 qWarning("File system model not initialized yet!");
2595                 return;
2596         }
2597         
2598         QString desktopPath = QDesktopServices::storageLocation(QDesktopServices::DesktopLocation);
2599         
2600         if(!desktopPath.isEmpty() && QDir(desktopPath).exists())
2601         {
2602                 ui->outputFolderView->setCurrentIndex(m_fileSystemModel->index(desktopPath));
2603                 outputFolderViewClicked(ui->outputFolderView->currentIndex());
2604                 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2605         }
2606         else
2607         {
2608                 ui->buttonGotoDesktop->setEnabled(false);
2609         }
2610 }
2611
2612 /*
2613  * Goto home folder button
2614  */
2615 void MainWindow::gotoHomeFolderButtonClicked(void)
2616 {
2617         if(!m_fileSystemModel)
2618         {
2619                 qWarning("File system model not initialized yet!");
2620                 return;
2621         }
2622
2623         QString homePath = QDesktopServices::storageLocation(QDesktopServices::HomeLocation);
2624         
2625         if(!homePath.isEmpty() && QDir(homePath).exists())
2626         {
2627                 ui->outputFolderView->setCurrentIndex(m_fileSystemModel->index(homePath));
2628                 outputFolderViewClicked(ui->outputFolderView->currentIndex());
2629                 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2630         }
2631         else
2632         {
2633                 ui->buttonGotoHome->setEnabled(false);
2634         }
2635 }
2636
2637 /*
2638  * Goto music folder button
2639  */
2640 void MainWindow::gotoMusicFolderButtonClicked(void)
2641 {
2642         if(!m_fileSystemModel)
2643         {
2644                 qWarning("File system model not initialized yet!");
2645                 return;
2646         }
2647
2648         QString musicPath = QDesktopServices::storageLocation(QDesktopServices::MusicLocation);
2649         
2650         if(!musicPath.isEmpty() && QDir(musicPath).exists())
2651         {
2652                 ui->outputFolderView->setCurrentIndex(m_fileSystemModel->index(musicPath));
2653                 outputFolderViewClicked(ui->outputFolderView->currentIndex());
2654                 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2655         }
2656         else
2657         {
2658                 ui->buttonGotoMusic->setEnabled(false);
2659         }
2660 }
2661
2662 /*
2663  * Goto music favorite output folder
2664  */
2665 void MainWindow::gotoFavoriteFolder(void)
2666 {
2667         if(!m_fileSystemModel)
2668         {
2669                 qWarning("File system model not initialized yet!");
2670                 return;
2671         }
2672
2673         QAction *item = dynamic_cast<QAction*>(QObject::sender());
2674         
2675         if(item)
2676         {
2677                 QDir path(item->data().toString());
2678                 if(path.exists())
2679                 {
2680                         ui->outputFolderView->setCurrentIndex(m_fileSystemModel->index(path.canonicalPath()));
2681                         outputFolderViewClicked(ui->outputFolderView->currentIndex());
2682                         CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2683                 }
2684                 else
2685                 {
2686                         MessageBeep(MB_ICONERROR);
2687                         m_outputFolderFavoritesMenu->removeAction(item);
2688                         item->deleteLater();
2689                 }
2690         }
2691 }
2692
2693 /*
2694  * Make folder button
2695  */
2696 void MainWindow::makeFolderButtonClicked(void)
2697 {
2698         ABORT_IF_BUSY;
2699
2700         if(!m_fileSystemModel)
2701         {
2702                 qWarning("File system model not initialized yet!");
2703                 return;
2704         }
2705
2706         QDir basePath(m_fileSystemModel->fileInfo(ui->outputFolderView->currentIndex()).absoluteFilePath());
2707         QString suggestedName = tr("New Folder");
2708
2709         if(!m_metaData->fileArtist().isEmpty() && !m_metaData->fileAlbum().isEmpty())
2710         {
2711                 suggestedName = QString("%1 - %2").arg(m_metaData->fileArtist(), m_metaData->fileAlbum());
2712         }
2713         else if(!m_metaData->fileArtist().isEmpty())
2714         {
2715                 suggestedName = m_metaData->fileArtist();
2716         }
2717         else if(!m_metaData->fileAlbum().isEmpty())
2718         {
2719                 suggestedName = m_metaData->fileAlbum();
2720         }
2721         else
2722         {
2723                 for(int i = 0; i < m_fileListModel->rowCount(); i++)
2724                 {
2725                         AudioFileModel audioFile = m_fileListModel->getFile(m_fileListModel->index(i, 0));
2726                         if(!audioFile.fileAlbum().isEmpty() || !audioFile.fileArtist().isEmpty())
2727                         {
2728                                 if(!audioFile.fileArtist().isEmpty() && !audioFile.fileAlbum().isEmpty())
2729                                 {
2730                                         suggestedName = QString("%1 - %2").arg(audioFile.fileArtist(), audioFile.fileAlbum());
2731                                 }
2732                                 else if(!audioFile.fileArtist().isEmpty())
2733                                 {
2734                                         suggestedName = audioFile.fileArtist();
2735                                 }
2736                                 else if(!audioFile.fileAlbum().isEmpty())
2737                                 {
2738                                         suggestedName = audioFile.fileAlbum();
2739                                 }
2740                                 break;
2741                         }
2742                 }
2743         }
2744         
2745         suggestedName = lamexp_clean_filename(suggestedName);
2746
2747         while(true)
2748         {
2749                 bool bApplied = false;
2750                 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();
2751
2752                 if(bApplied)
2753                 {
2754                         folderName = lamexp_clean_filepath(folderName.simplified());
2755
2756                         if(folderName.isEmpty())
2757                         {
2758                                 MessageBeep(MB_ICONERROR);
2759                                 continue;
2760                         }
2761
2762                         int i = 1;
2763                         QString newFolder = folderName;
2764
2765                         while(basePath.exists(newFolder))
2766                         {
2767                                 newFolder = QString(folderName).append(QString().sprintf(" (%d)", ++i));
2768                         }
2769                         
2770                         if(basePath.mkpath(newFolder))
2771                         {
2772                                 QDir createdDir = basePath;
2773                                 if(createdDir.cd(newFolder))
2774                                 {
2775                                         QModelIndex newIndex = m_fileSystemModel->index(createdDir.canonicalPath());
2776                                         ui->outputFolderView->setCurrentIndex(newIndex);
2777                                         outputFolderViewClicked(newIndex);
2778                                         CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2779                                 }
2780                         }
2781                         else
2782                         {
2783                                 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!")));
2784                         }
2785                 }
2786                 break;
2787         }
2788 }
2789
2790 /*
2791  * Output to source dir changed
2792  */
2793 void MainWindow::saveToSourceFolderChanged(void)
2794 {
2795         m_settings->outputToSourceDir(ui->saveToSourceFolderCheckBox->isChecked());
2796 }
2797
2798 /*
2799  * Prepend relative source file path to output file name changed
2800  */
2801 void MainWindow::prependRelativePathChanged(void)
2802 {
2803         m_settings->prependRelativeSourcePath(ui->prependRelativePathCheckBox->isChecked());
2804 }
2805
2806 /*
2807  * Show context menu for output folder
2808  */
2809 void MainWindow::outputFolderContextMenu(const QPoint &pos)
2810 {
2811         QAbstractScrollArea *scrollArea = dynamic_cast<QAbstractScrollArea*>(QObject::sender());
2812         QWidget *sender = scrollArea ? scrollArea->viewport() : dynamic_cast<QWidget*>(QObject::sender());      
2813
2814         if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0)
2815         {
2816                 m_outputFolderContextMenu->popup(sender->mapToGlobal(pos));
2817         }
2818 }
2819
2820 /*
2821  * Show selected folder in explorer
2822  */
2823 void MainWindow::showFolderContextActionTriggered(void)
2824 {
2825         if(!m_fileSystemModel)
2826         {
2827                 qWarning("File system model not initialized yet!");
2828                 return;
2829         }
2830
2831         QString path = QDir::toNativeSeparators(m_fileSystemModel->filePath(ui->outputFolderView->currentIndex()));
2832         if(!path.endsWith(QDir::separator())) path.append(QDir::separator());
2833         ShellExecuteW(reinterpret_cast<HWND>(this->winId()), L"explore", QWCHAR(path), NULL, NULL, SW_SHOW);
2834 }
2835
2836 /*
2837  * Refresh the directory outline
2838  */
2839 void MainWindow::refreshFolderContextActionTriggered(void)
2840 {
2841         //force re-initialization
2842         QTimer::singleShot(0, this, SLOT(initOutputFolderModel()));
2843 }
2844
2845 /*
2846  * Add current folder to favorites
2847  */
2848 void MainWindow::addFavoriteFolderActionTriggered(void)
2849 {
2850         QString path = m_fileSystemModel->filePath(ui->outputFolderView->currentIndex());
2851         QStringList favorites = m_settings->favoriteOutputFolders().split("|", QString::SkipEmptyParts);
2852
2853         if(!favorites.contains(path, Qt::CaseInsensitive))
2854         {
2855                 favorites.append(path);
2856                 while(favorites.count() > 6) favorites.removeFirst();
2857         }
2858         else
2859         {
2860                 MessageBeep(MB_ICONWARNING);
2861         }
2862
2863         m_settings->favoriteOutputFolders(favorites.join("|"));
2864         refreshFavorites();
2865 }
2866
2867 /*
2868  * Output folder edit finished
2869  */
2870 void MainWindow::outputFolderEditFinished(void)
2871 {
2872         if(ui->outputFolderEdit->isHidden())
2873         {
2874                 return; //Not currently in edit mode!
2875         }
2876         
2877         bool ok = false;
2878         
2879         QString text = QDir::fromNativeSeparators(ui->outputFolderEdit->text().trimmed());
2880         while(text.startsWith('"') || text.startsWith('/')) text = text.right(text.length() - 1).trimmed();
2881         while(text.endsWith('"') || text.endsWith('/')) text = text.left(text.length() - 1).trimmed();
2882
2883         static const char *str = "?*<>|\"";
2884         for(size_t i = 0; str[i]; i++) text.replace(str[i], "_");
2885
2886         if(!((text.length() >= 2) && text.at(0).isLetter() && text.at(1) == QChar(':')))
2887         {
2888                 text = QString("%1/%2").arg(QDir::fromNativeSeparators(ui->outputFolderLabel->text()), text);
2889         }
2890
2891         if(text.length() == 2) text += "/"; /* "X:" => "X:/" */
2892
2893         while(text.length() > 2)
2894         {
2895                 QFileInfo info(text);
2896                 if(info.exists() && info.isDir())
2897                 {
2898                         QModelIndex index = m_fileSystemModel->index(QFileInfo(info.canonicalFilePath()).absoluteFilePath());
2899                         if(index.isValid())
2900                         {
2901                                 ok = true;
2902                                 ui->outputFolderView->setCurrentIndex(index);
2903                                 outputFolderViewClicked(index);
2904                                 break;
2905                         }
2906                 }
2907                 else if(info.exists() && info.isFile())
2908                 {
2909                         QModelIndex index = m_fileSystemModel->index(QFileInfo(info.canonicalPath()).absoluteFilePath());
2910                         if(index.isValid())
2911                         {
2912                                 ok = true;
2913                                 ui->outputFolderView->setCurrentIndex(index);
2914                                 outputFolderViewClicked(index);
2915                                 break;
2916                         }
2917                 }
2918
2919                 text = text.left(text.length() - 1).trimmed();
2920         }
2921
2922         ui->outputFolderEdit->setVisible(false);
2923         ui->outputFolderLabel->setVisible(true);
2924         ui->outputFolderView->setEnabled(true);
2925
2926         if(!ok) MessageBeep(MB_ICONERROR);
2927         CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2928 }
2929
2930 /*
2931  * Initialize file system model
2932  */
2933 void MainWindow::initOutputFolderModel(void)
2934 {
2935         if(m_outputFolderNoteBox->isHidden())
2936         {
2937                 m_outputFolderNoteBox->show();
2938                 m_outputFolderNoteBox->repaint();
2939                 m_outputFolderViewInitCounter = 4;
2940
2941                 if(m_fileSystemModel)
2942                 {
2943                         SET_MODEL(ui->outputFolderView, NULL);
2944                         LAMEXP_DELETE(m_fileSystemModel);
2945                         ui->outputFolderView->repaint();
2946                 }
2947
2948                 if(m_fileSystemModel = new QFileSystemModelEx())
2949                 {
2950                         m_fileSystemModel->installEventFilter(this);
2951                         connect(m_fileSystemModel, SIGNAL(directoryLoaded(QString)), this, SLOT(outputFolderDirectoryLoaded(QString)));
2952                         connect(m_fileSystemModel, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(outputFolderRowsInserted(QModelIndex,int,int)));
2953
2954                         SET_MODEL(ui->outputFolderView, m_fileSystemModel);
2955                         ui->outputFolderView->header()->setStretchLastSection(true);
2956                         ui->outputFolderView->header()->hideSection(1);
2957                         ui->outputFolderView->header()->hideSection(2);
2958                         ui->outputFolderView->header()->hideSection(3);
2959                 
2960                         m_fileSystemModel->setRootPath("");
2961                         QModelIndex index = m_fileSystemModel->index(m_settings->outputDir());
2962                         if(index.isValid()) ui->outputFolderView->setCurrentIndex(index);
2963                         outputFolderViewClicked(ui->outputFolderView->currentIndex());
2964                 }
2965
2966                 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2967                 QTimer::singleShot(125, this, SLOT(initOutputFolderModel_doAsync()));
2968         }
2969 }
2970
2971 /*
2972  * Initialize file system model (do NOT call this one directly!)
2973  */
2974 void MainWindow::initOutputFolderModel_doAsync(void)
2975 {
2976         if(m_outputFolderViewInitCounter > 0)
2977         {
2978                 m_outputFolderViewInitCounter--;
2979                 QTimer::singleShot(125, this, SLOT(initOutputFolderModel_doAsync()));
2980         }
2981         else
2982         {
2983                 QTimer::singleShot(125, m_outputFolderNoteBox, SLOT(hide()));
2984                 ui->outputFolderView->setFocus();
2985         }
2986 }
2987
2988 /*
2989  * Center current folder in view
2990  */
2991 void MainWindow::centerOutputFolderModel(void)
2992 {
2993         if(ui->outputFolderView->isVisible())
2994         {
2995                 centerOutputFolderModel_doAsync();
2996                 QTimer::singleShot(125, this, SLOT(centerOutputFolderModel_doAsync()));
2997         }
2998 }
2999
3000 /*
3001  * Center current folder in view (do NOT call this one directly!)
3002  */
3003 void MainWindow::centerOutputFolderModel_doAsync(void)
3004 {
3005         if(ui->outputFolderView->isVisible())
3006         {
3007                 m_outputFolderViewCentering = true;
3008                 const QModelIndex index = ui->outputFolderView->currentIndex();
3009                 ui->outputFolderView->scrollTo(index, QAbstractItemView::PositionAtCenter);
3010                 ui->outputFolderView->setFocus();
3011         }
3012 }
3013
3014 /*
3015  * File system model asynchronously loaded a dir
3016  */
3017 void MainWindow::outputFolderDirectoryLoaded(const QString &path)
3018 {
3019         if(m_outputFolderViewCentering)
3020         {
3021                 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
3022         }
3023 }
3024
3025 /*
3026  * File system model inserted new items
3027  */
3028 void MainWindow::outputFolderRowsInserted(const QModelIndex &parent, int start, int end)
3029 {
3030         if(m_outputFolderViewCentering)
3031         {
3032                 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
3033         }
3034 }
3035
3036 /*
3037  * Directory view item was expanded by user
3038  */
3039 void MainWindow::outputFolderItemExpanded(const QModelIndex &item)
3040 {
3041         //We need to stop centering as soon as the user has expanded an item manually!
3042         m_outputFolderViewCentering = false;
3043 }
3044
3045 /*
3046  * View event for output folder control occurred
3047  */
3048 void MainWindow::outputFolderViewEventOccurred(QWidget *sender, QEvent *event)
3049 {
3050         switch(event->type())
3051         {
3052         case QEvent::Enter:
3053         case QEvent::Leave:
3054         case QEvent::KeyPress:
3055         case QEvent::KeyRelease:
3056         case QEvent::FocusIn:
3057         case QEvent::FocusOut:
3058         case QEvent::TouchEnd:
3059                 outputFolderViewClicked(ui->outputFolderView->currentIndex());
3060                 break;
3061         }
3062 }
3063
3064 /*
3065  * Mouse event for output folder control occurred
3066  */
3067 void MainWindow::outputFolderMouseEventOccurred(QWidget *sender, QEvent *event)
3068 {
3069         QMouseEvent *mouseEvent = dynamic_cast<QMouseEvent*>(event);
3070         QPoint pos = (mouseEvent) ? mouseEvent->pos() : QPoint();
3071
3072         if(sender == ui->outputFolderLabel)
3073         {
3074                 switch(event->type())
3075                 {
3076                 case QEvent::MouseButtonPress:
3077                         if(mouseEvent && (mouseEvent->button() == Qt::LeftButton))
3078                         {
3079                                 QString path = ui->outputFolderLabel->text();
3080                                 if(!path.endsWith(QDir::separator())) path.append(QDir::separator());
3081                                 ShellExecuteW(reinterpret_cast<HWND>(this->winId()), L"explore", QWCHAR(path), NULL, NULL, SW_SHOW);
3082                         }
3083                         break;
3084                 case QEvent::Enter:
3085                         ui->outputFolderLabel->setForegroundRole(QPalette::Link);
3086                         break;
3087                 case QEvent::Leave:
3088                         ui->outputFolderLabel->setForegroundRole(QPalette::WindowText);
3089                         break;
3090                 }
3091         }
3092         else if(sender == ui->outputFoldersFovoritesLabel)
3093         {
3094                 switch(event->type())
3095                 {
3096                 case QEvent::Enter:
3097                         ui->outputFoldersFovoritesLabel->setFrameShadow(QFrame::Raised);
3098                         break;
3099                 case QEvent::MouseButtonPress:
3100                         ui->outputFoldersFovoritesLabel->setFrameShadow(QFrame::Sunken);
3101                         break;
3102                 case QEvent::MouseButtonRelease:
3103                         ui->outputFoldersFovoritesLabel->setFrameShadow(QFrame::Raised);
3104                         if(mouseEvent)
3105                         {
3106                                 if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0 && mouseEvent->button() != Qt::MidButton)
3107                                 {
3108                                         if(ui->outputFolderView->isEnabled())
3109                                         {
3110                                                 m_outputFolderFavoritesMenu->popup(sender->mapToGlobal(pos));
3111                                         }
3112                                 }
3113                         }
3114                         break;
3115                 case QEvent::Leave:
3116                         ui->outputFoldersFovoritesLabel->setFrameShadow(QFrame::Plain);
3117                         break;
3118                 }
3119         }
3120         else if(sender == ui->outputFoldersEditorLabel)
3121         {
3122                 switch(event->type())
3123                 {
3124                 case QEvent::Enter:
3125                         ui->outputFoldersEditorLabel->setFrameShadow(QFrame::Raised);
3126                         break;
3127                 case QEvent::MouseButtonPress:
3128                         ui->outputFoldersEditorLabel->setFrameShadow(QFrame::Sunken);
3129                         break;
3130                 case QEvent::MouseButtonRelease:
3131                         ui->outputFoldersEditorLabel->setFrameShadow(QFrame::Raised);
3132                         if(mouseEvent)
3133                         {
3134                                 if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0 && mouseEvent->button() != Qt::MidButton)
3135                                 {
3136                                         if(ui->outputFolderView->isEnabled())
3137                                         {
3138                                                 ui->outputFolderView->setEnabled(false);
3139                                                 ui->outputFolderLabel->setVisible(false);
3140                                                 ui->outputFolderEdit->setVisible(true);
3141                                                 ui->outputFolderEdit->setText(ui->outputFolderLabel->text());
3142                                                 ui->outputFolderEdit->selectAll();
3143                                                 ui->outputFolderEdit->setFocus();
3144                                         }
3145                                 }
3146                         }
3147                         break;
3148                 case QEvent::Leave:
3149                         ui->outputFoldersEditorLabel->setFrameShadow(QFrame::Plain);
3150                         break;
3151                 }
3152         }
3153 }
3154
3155 // =========================================================
3156 // Metadata tab slots
3157 // =========================================================
3158
3159 /*
3160  * Edit meta button clicked
3161  */
3162 void MainWindow::editMetaButtonClicked(void)
3163 {
3164         ABORT_IF_BUSY;
3165
3166         const QModelIndex index = ui->metaDataView->currentIndex();
3167
3168         if(index.isValid())
3169         {
3170                 m_metaInfoModel->editItem(index, this);
3171         
3172                 if(index.row() == 4)
3173                 {
3174                         m_settings->metaInfoPosition(m_metaData->filePosition());
3175                 }
3176         }
3177 }
3178
3179 /*
3180  * Reset meta button clicked
3181  */
3182 void MainWindow::clearMetaButtonClicked(void)
3183 {
3184         ABORT_IF_BUSY;
3185         m_metaInfoModel->clearData();
3186 }
3187
3188 /*
3189  * Meta tags enabled changed
3190  */
3191 void MainWindow::metaTagsEnabledChanged(void)
3192 {
3193         m_settings->writeMetaTags(ui->writeMetaDataCheckBox->isChecked());
3194 }
3195
3196 /*
3197  * Playlist enabled changed
3198  */
3199 void MainWindow::playlistEnabledChanged(void)
3200 {
3201         m_settings->createPlaylist(ui->generatePlaylistCheckBox->isChecked());
3202 }
3203
3204 // =========================================================
3205 // Compression tab slots
3206 // =========================================================
3207
3208 /*
3209  * Update encoder
3210  */
3211 void MainWindow::updateEncoder(int id)
3212 {
3213         m_settings->compressionEncoder(id);
3214
3215         switch(m_settings->compressionEncoder())
3216         {
3217         case SettingsModel::VorbisEncoder:
3218                 ui->radioButtonModeQuality->setEnabled(true);
3219                 ui->radioButtonModeAverageBitrate->setEnabled(true);
3220                 ui->radioButtonConstBitrate->setEnabled(false);
3221                 if(ui->radioButtonConstBitrate->isChecked()) ui->radioButtonModeQuality->setChecked(true);
3222                 ui->sliderBitrate->setEnabled(true);
3223                 break;
3224         case SettingsModel::AC3Encoder:
3225                 ui->radioButtonModeQuality->setEnabled(true);
3226                 ui->radioButtonModeQuality->setChecked(true);
3227                 ui->radioButtonModeAverageBitrate->setEnabled(false);
3228                 ui->radioButtonConstBitrate->setEnabled(true);
3229                 ui->sliderBitrate->setEnabled(true);
3230                 break;
3231         case SettingsModel::FLACEncoder:
3232                 ui->radioButtonModeQuality->setEnabled(false);
3233                 ui->radioButtonModeQuality->setChecked(true);
3234                 ui->radioButtonModeAverageBitrate->setEnabled(false);
3235                 ui->radioButtonConstBitrate->setEnabled(false);
3236                 ui->sliderBitrate->setEnabled(true);
3237                 break;
3238         case SettingsModel::PCMEncoder:
3239                 ui->radioButtonModeQuality->setEnabled(false);
3240                 ui->radioButtonModeQuality->setChecked(true);
3241                 ui->radioButtonModeAverageBitrate->setEnabled(false);
3242                 ui->radioButtonConstBitrate->setEnabled(false);
3243                 ui->sliderBitrate->setEnabled(false);
3244                 break;
3245         case SettingsModel::AACEncoder:
3246                 ui->radioButtonModeQuality->setEnabled(true);
3247                 ui->radioButtonModeAverageBitrate->setEnabled(!m_fhgEncoderAvailable);
3248                 if(m_fhgEncoderAvailable && ui->radioButtonModeAverageBitrate->isChecked()) ui->radioButtonConstBitrate->setChecked(true);
3249                 ui->radioButtonConstBitrate->setEnabled(true);
3250                 ui->sliderBitrate->setEnabled(true);
3251                 break;
3252         case SettingsModel::DCAEncoder:
3253                 ui->radioButtonModeQuality->setEnabled(false);
3254                 ui->radioButtonModeAverageBitrate->setEnabled(false);
3255                 ui->radioButtonConstBitrate->setEnabled(true);
3256                 ui->radioButtonConstBitrate->setChecked(true);
3257                 ui->sliderBitrate->setEnabled(true);
3258                 break;
3259         default:
3260                 ui->radioButtonModeQuality->setEnabled(true);
3261                 ui->radioButtonModeAverageBitrate->setEnabled(true);
3262                 ui->radioButtonConstBitrate->setEnabled(true);
3263                 ui->sliderBitrate->setEnabled(true);
3264                 break;
3265         }
3266
3267         if(m_settings->compressionEncoder() == SettingsModel::AACEncoder)
3268         {
3269                 const QString encoderName = m_qaacEncoderAvailable ? tr("QAAC (Apple)") : (m_fhgEncoderAvailable ? tr("FHG AAC (Winamp)") : (m_neroEncoderAvailable ? tr("Nero AAC") : tr("Not available!")));
3270                 ui->labelEncoderInfo->setVisible(true);
3271                 ui->labelEncoderInfo->setText(tr("Current AAC Encoder: %1").arg(encoderName));
3272         }
3273         else
3274         {
3275                 ui->labelEncoderInfo->setVisible(false);
3276         }
3277
3278         updateRCMode(m_modeButtonGroup->checkedId());
3279 }
3280
3281 /*
3282  * Update rate-control mode
3283  */
3284 void MainWindow::updateRCMode(int id)
3285 {
3286         m_settings->compressionRCMode(id);
3287
3288         switch(m_settings->compressionEncoder())
3289         {
3290         case SettingsModel::MP3Encoder:
3291                 switch(m_settings->compressionRCMode())
3292                 {
3293                 case SettingsModel::VBRMode:
3294                         ui->sliderBitrate->setMinimum(0);
3295                         ui->sliderBitrate->setMaximum(9);
3296                         break;
3297                 default:
3298                         ui->sliderBitrate->setMinimum(0);
3299                         ui->sliderBitrate->setMaximum(13);
3300                         break;
3301                 }
3302                 break;
3303         case SettingsModel::VorbisEncoder:
3304                 switch(m_settings->compressionRCMode())
3305                 {
3306                 case SettingsModel::VBRMode:
3307                         ui->sliderBitrate->setMinimum(-2);
3308                         ui->sliderBitrate->setMaximum(10);
3309                         break;
3310                 default:
3311                         ui->sliderBitrate->setMinimum(4);
3312                         ui->sliderBitrate->setMaximum(63);
3313                         break;
3314                 }
3315                 break;
3316         case SettingsModel::AC3Encoder:
3317                 switch(m_settings->compressionRCMode())
3318                 {
3319                 case SettingsModel::VBRMode:
3320                         ui->sliderBitrate->setMinimum(0);
3321                         ui->sliderBitrate->setMaximum(16);
3322                         break;
3323                 default:
3324                         ui->sliderBitrate->setMinimum(0);
3325                         ui->sliderBitrate->setMaximum(18);
3326                         break;
3327                 }
3328                 break;
3329         case SettingsModel::AACEncoder:
3330                 switch(m_settings->compressionRCMode())
3331                 {
3332                 case SettingsModel::VBRMode:
3333                         ui->sliderBitrate->setMinimum(0);
3334                         ui->sliderBitrate->setMaximum(20);
3335                         break;
3336                 default:
3337                         ui->sliderBitrate->setMinimum(4);
3338                         ui->sliderBitrate->setMaximum(63);
3339                         break;
3340                 }
3341                 break;
3342         case SettingsModel::FLACEncoder:
3343                 ui->sliderBitrate->setMinimum(0);
3344                 ui->sliderBitrate->setMaximum(8);
3345                 break;
3346         case SettingsModel::OpusEncoder:
3347                 ui->sliderBitrate->setMinimum(1);
3348                 ui->sliderBitrate->setMaximum(32);
3349                 break;
3350         case SettingsModel::DCAEncoder:
3351                 ui->sliderBitrate->setMinimum(1);
3352                 ui->sliderBitrate->setMaximum(128);
3353                 break;
3354         case SettingsModel::PCMEncoder:
3355                 ui->sliderBitrate->setMinimum(0);
3356                 ui->sliderBitrate->setMaximum(2);
3357                 ui->sliderBitrate->setValue(1);
3358                 break;
3359         default:
3360                 ui->sliderBitrate->setMinimum(0);
3361                 ui->sliderBitrate->setMaximum(0);
3362                 break;
3363         }
3364
3365         updateBitrate(ui->sliderBitrate->value());
3366 }
3367
3368 /*
3369  * Update bitrate
3370  */
3371 void MainWindow::updateBitrate(int value)
3372 {
3373         m_settings->compressionBitrate(value);
3374         
3375         switch(m_settings->compressionRCMode())
3376         {
3377         case SettingsModel::VBRMode:
3378                 switch(m_settings->compressionEncoder())
3379                 {
3380                 case SettingsModel::MP3Encoder:
3381                         ui->labelBitrate->setText(tr("Quality Level %1").arg(9 - value));
3382                         break;
3383                 case SettingsModel::VorbisEncoder:
3384                         ui->labelBitrate->setText(tr("Quality Level %1").arg(value));
3385                         break;
3386                 case SettingsModel::AACEncoder:
3387                         ui->labelBitrate->setText(tr("Quality Level %1").arg(QString().sprintf("%.2f", static_cast<double>(value * 5) / 100.0)));
3388                         break;
3389                 case SettingsModel::FLACEncoder:
3390                         ui->labelBitrate->setText(tr("Compression %1").arg(value));
3391                         break;
3392                 case SettingsModel::OpusEncoder:
3393                         ui->labelBitrate->setText(QString("&asymp; %1 kbps").arg(qMin(500, value * 8)));
3394                         break;
3395                 case SettingsModel::AC3Encoder:
3396                         ui->labelBitrate->setText(tr("Quality Level %1").arg(qMin(1024, qMax(0, value * 64))));
3397                         break;
3398                 case SettingsModel::PCMEncoder:
3399                         ui->labelBitrate->setText(tr("Uncompressed"));
3400                         break;
3401                 default:
3402                         ui->labelBitrate->setText(QString::number(value));
3403                         break;
3404                 }
3405                 break;
3406         case SettingsModel::ABRMode:
3407                 switch(m_settings->compressionEncoder())
3408                 {
3409                 case SettingsModel::MP3Encoder:
3410                         ui->labelBitrate->setText(QString("&asymp; %1 kbps").arg(SettingsModel::mp3Bitrates[value]));
3411                         break;
3412                 case SettingsModel::FLACEncoder:
3413                         ui->labelBitrate->setText(tr("Compression %1").arg(value));
3414                         break;
3415                 case SettingsModel::AC3Encoder:
3416                         ui->labelBitrate->setText(QString("&asymp; %1 kbps").arg(SettingsModel::ac3Bitrates[value]));
3417                         break;
3418                 case SettingsModel::PCMEncoder:
3419                         ui->labelBitrate->setText(tr("Uncompressed"));
3420                         break;
3421                 default:
3422                         ui->labelBitrate->setText(QString("&asymp; %1 kbps").arg(qMin(500, value * 8)));
3423                         break;
3424                 }
3425                 break;
3426         default:
3427                 switch(m_settings->compressionEncoder())
3428                 {
3429                 case SettingsModel::MP3Encoder:
3430                         ui->labelBitrate->setText(QString("%1 kbps").arg(SettingsModel::mp3Bitrates[value]));
3431                         break;
3432                 case SettingsModel::FLACEncoder:
3433                         ui->labelBitrate->setText(tr("Compression %1").arg(value));
3434                         break;
3435                 case SettingsModel::AC3Encoder:
3436                         ui->labelBitrate->setText(QString("%1 kbps").arg(SettingsModel::ac3Bitrates[value]));
3437                         break;
3438                 case SettingsModel::DCAEncoder:
3439                         ui->labelBitrate->setText(QString("%1 kbps").arg(value * 32));
3440                         break;
3441                 case SettingsModel::PCMEncoder:
3442                         ui->labelBitrate->setText(tr("Uncompressed"));
3443                         break;
3444                 default:
3445                         ui->labelBitrate->setText(QString("%1 kbps").arg(qMin(500, value * 8)));
3446                         break;
3447                 }
3448                 break;
3449         }
3450 }
3451
3452 /*
3453  * Event for compression tab occurred
3454  */
3455 void MainWindow::compressionTabEventOccurred(QWidget *sender, QEvent *event)
3456 {
3457         static const QUrl helpUrl("http://lamexp.sourceforge.net/doc/FAQ.html#054010d9");
3458         
3459         if((sender == ui->labelCompressionHelp) && (event->type() == QEvent::MouseButtonPress))
3460         {
3461                 QDesktopServices::openUrl(helpUrl);
3462         }
3463 }
3464
3465 // =========================================================
3466 // Advanced option slots
3467 // =========================================================
3468
3469 /*
3470  * Lame algorithm quality changed
3471  */
3472 void MainWindow::updateLameAlgoQuality(int value)
3473 {
3474         QString text;
3475
3476         switch(value)
3477         {
3478         case 4:
3479                 text = tr("Best Quality (Very Slow)");
3480                 break;
3481         case 3:
3482                 text = tr("High Quality (Recommended)");
3483                 break;
3484         case 2:
3485                 text = tr("Average Quality (Default)");
3486                 break;
3487         case 1:
3488                 text = tr("Low Quality (Fast)");
3489                 break;
3490         case 0:
3491                 text = tr("Poor Quality (Very Fast)");
3492                 break;
3493         }
3494
3495         if(!text.isEmpty())
3496         {
3497                 m_settings->lameAlgoQuality(value);
3498                 ui->labelLameAlgoQuality->setText(text);
3499         }
3500
3501         bool warning = (value == 0), notice = (value == 4);
3502         ui->labelLameAlgoQualityWarning->setVisible(warning);
3503         ui->labelLameAlgoQualityWarningIcon->setVisible(warning);
3504         ui->labelLameAlgoQualityNotice->setVisible(notice);
3505         ui->labelLameAlgoQualityNoticeIcon->setVisible(notice);
3506         ui->labelLameAlgoQualitySpacer->setVisible(warning || notice);
3507 }
3508
3509 /*
3510  * Bitrate management endabled/disabled
3511  */
3512 void MainWindow::bitrateManagementEnabledChanged(bool checked)
3513 {
3514         m_settings->bitrateManagementEnabled(checked);
3515 }
3516
3517 /*
3518  * Minimum bitrate has changed
3519  */
3520 void MainWindow::bitrateManagementMinChanged(int value)
3521 {
3522         if(value > ui->spinBoxBitrateManagementMax->value())
3523         {
3524                 ui->spinBoxBitrateManagementMin->setValue(ui->spinBoxBitrateManagementMax->value());
3525                 m_settings->bitrateManagementMinRate(ui->spinBoxBitrateManagementMax->value());
3526         }
3527         else
3528         {
3529                 m_settings->bitrateManagementMinRate(value);
3530         }
3531 }
3532
3533 /*
3534  * Maximum bitrate has changed
3535  */
3536 void MainWindow::bitrateManagementMaxChanged(int value)
3537 {
3538         if(value < ui->spinBoxBitrateManagementMin->value())
3539         {
3540                 ui->spinBoxBitrateManagementMax->setValue(ui->spinBoxBitrateManagementMin->value());
3541                 m_settings->bitrateManagementMaxRate(ui->spinBoxBitrateManagementMin->value());
3542         }
3543         else
3544         {
3545                 m_settings->bitrateManagementMaxRate(value);
3546         }
3547 }
3548
3549 /*
3550  * Channel mode has changed
3551  */
3552 void MainWindow::channelModeChanged(int value)
3553 {
3554         if(value >= 0) m_settings->lameChannelMode(value);
3555 }
3556
3557 /*
3558  * Sampling rate has changed
3559  */
3560 void MainWindow::samplingRateChanged(int value)
3561 {
3562         if(value >= 0) m_settings->samplingRate(value);
3563 }
3564
3565 /*
3566  * Nero AAC 2-Pass mode changed
3567  */
3568 void MainWindow::neroAAC2PassChanged(bool checked)
3569 {
3570         m_settings->neroAACEnable2Pass(checked);
3571 }
3572
3573 /*
3574  * Nero AAC profile mode changed
3575  */
3576 void MainWindow::neroAACProfileChanged(int value)
3577 {
3578         if(value >= 0) m_settings->aacEncProfile(value);
3579 }
3580
3581 /*
3582  * Aften audio coding mode changed
3583  */
3584 void MainWindow::aftenCodingModeChanged(int value)
3585 {
3586         if(value >= 0) m_settings->aftenAudioCodingMode(value);
3587 }
3588
3589 /*
3590  * Aften DRC mode changed
3591  */
3592 void MainWindow::aftenDRCModeChanged(int value)
3593 {
3594         if(value >= 0) m_settings->aftenDynamicRangeCompression(value);
3595 }
3596
3597 /*
3598  * Aften exponent search size changed
3599  */
3600 void MainWindow::aftenSearchSizeChanged(int value)
3601 {
3602         if(value >= 0) m_settings->aftenExponentSearchSize(value);
3603 }
3604
3605 /*
3606  * Aften fast bit allocation changed
3607  */
3608 void MainWindow::aftenFastAllocationChanged(bool checked)
3609 {
3610         m_settings->aftenFastBitAllocation(checked);
3611 }
3612
3613
3614 /*
3615  * Opus encoder settings changed
3616  */
3617 void MainWindow::opusSettingsChanged(void)
3618 {
3619         m_settings->opusFramesize(ui->comboBoxOpusFramesize->currentIndex());
3620         m_settings->opusComplexity(ui->spinBoxOpusComplexity->value());
3621         //m_settings->opusOptimizeFor(comboBoxOpusOptimize->currentIndex());
3622 }
3623
3624 /*
3625  * Normalization filter enabled changed
3626  */
3627 void MainWindow::normalizationEnabledChanged(bool checked)
3628 {
3629         m_settings->normalizationFilterEnabled(checked);
3630 }
3631
3632 /*
3633  * Normalization max. volume changed
3634  */
3635 void MainWindow::normalizationMaxVolumeChanged(double value)
3636 {
3637         m_settings->normalizationFilterMaxVolume(static_cast<int>(value * 100.0));
3638 }
3639
3640 /*
3641  * Normalization equalization mode changed
3642  */
3643 void MainWindow::normalizationModeChanged(int mode)
3644 {
3645         m_settings->normalizationFilterEqualizationMode(mode);
3646 }
3647
3648 /*
3649  * Tone adjustment has changed (Bass)
3650  */
3651 void MainWindow::toneAdjustBassChanged(double value)
3652 {
3653         m_settings->toneAdjustBass(static_cast<int>(value * 100.0));
3654         ui->spinBoxToneAdjustBass->setPrefix((value > 0) ? "+" : QString());
3655 }
3656
3657 /*
3658  * Tone adjustment has changed (Treble)
3659  */
3660 void MainWindow::toneAdjustTrebleChanged(double value)
3661 {
3662         m_settings->toneAdjustTreble(static_cast<int>(value * 100.0));
3663         ui->spinBoxToneAdjustTreble->setPrefix((value > 0) ? "+" : QString());
3664 }
3665
3666 /*
3667  * Tone adjustment has been reset
3668  */
3669 void MainWindow::toneAdjustTrebleReset(void)
3670 {
3671         ui->spinBoxToneAdjustBass->setValue(m_settings->toneAdjustBassDefault());
3672         ui->spinBoxToneAdjustTreble->setValue(m_settings->toneAdjustTrebleDefault());
3673         toneAdjustBassChanged(ui->spinBoxToneAdjustBass->value());
3674         toneAdjustTrebleChanged(ui->spinBoxToneAdjustTreble->value());
3675 }
3676
3677 /*
3678  * Custom encoder parameters changed
3679  */
3680 void MainWindow::customParamsChanged(void)
3681 {
3682         ui->lineEditCustomParamLAME->setText(ui->lineEditCustomParamLAME->text().simplified());
3683         ui->lineEditCustomParamOggEnc->setText(ui->lineEditCustomParamOggEnc->text().simplified());
3684         ui->lineEditCustomParamNeroAAC->setText(ui->lineEditCustomParamNeroAAC->text().simplified());
3685         ui->lineEditCustomParamFLAC->setText(ui->lineEditCustomParamFLAC->text().simplified());
3686         ui->lineEditCustomParamAften->setText(ui->lineEditCustomParamAften->text().simplified());
3687         ui->lineEditCustomParamOpus->setText(ui->lineEditCustomParamOpus->text().simplified());
3688
3689         bool customParamsUsed = false;
3690         if(!ui->lineEditCustomParamLAME->text().isEmpty()) customParamsUsed = true;
3691         if(!ui->lineEditCustomParamOggEnc->text().isEmpty()) customParamsUsed = true;
3692         if(!ui->lineEditCustomParamNeroAAC->text().isEmpty()) customParamsUsed = true;
3693         if(!ui->lineEditCustomParamFLAC->text().isEmpty()) customParamsUsed = true;
3694         if(!ui->lineEditCustomParamAften->text().isEmpty()) customParamsUsed = true;
3695         if(!ui->lineEditCustomParamOpus->text().isEmpty()) customParamsUsed = true;
3696
3697         ui->labelCustomParamsIcon->setVisible(customParamsUsed);
3698         ui->labelCustomParamsText->setVisible(customParamsUsed);
3699         ui->labelCustomParamsSpacer->setVisible(customParamsUsed);
3700
3701         m_settings->customParametersLAME(ui->lineEditCustomParamLAME->text());
3702         m_settings->customParametersOggEnc(ui->lineEditCustomParamOggEnc->text());
3703         m_settings->customParametersAacEnc(ui->lineEditCustomParamNeroAAC->text());
3704         m_settings->customParametersFLAC(ui->lineEditCustomParamFLAC->text());
3705         m_settings->customParametersAften(ui->lineEditCustomParamAften->text());
3706         m_settings->customParametersOpus(ui->lineEditCustomParamOpus->text());
3707 }
3708
3709 /*
3710  * Rename output files enabled changed
3711  */
3712 void MainWindow::renameOutputEnabledChanged(bool checked)
3713 {
3714         m_settings->renameOutputFilesEnabled(checked);
3715 }
3716
3717 /*
3718  * Rename output files patterm changed
3719  */
3720 void MainWindow::renameOutputPatternChanged(void)
3721 {
3722         QString temp = ui->lineEditRenamePattern->text().simplified();
3723         ui->lineEditRenamePattern->setText(temp.isEmpty() ? m_settings->renameOutputFilesPatternDefault() : temp);
3724         m_settings->renameOutputFilesPattern(ui->lineEditRenamePattern->text());
3725 }
3726
3727 /*
3728  * Rename output files patterm changed
3729  */
3730 void MainWindow::renameOutputPatternChanged(const QString &text)
3731 {
3732         QString pattern(text.simplified());
3733         
3734         pattern.replace("<BaseName>", "The_White_Stripes_-_Fell_In_Love_With_A_Girl", Qt::CaseInsensitive);
3735         pattern.replace("<TrackNo>", "04", Qt::CaseInsensitive);
3736         pattern.replace("<Title>", "Fell In Love With A Girl", Qt::CaseInsensitive);
3737         pattern.replace("<Artist>", "The White Stripes", Qt::CaseInsensitive);
3738         pattern.replace("<Album>", "White Blood Cells", Qt::CaseInsensitive);
3739         pattern.replace("<Year>", "2001", Qt::CaseInsensitive);
3740         pattern.replace("<Comment>", "Encoded by LameXP", Qt::CaseInsensitive);
3741
3742         if(pattern.compare(lamexp_clean_filename(pattern)))
3743         {
3744                 if(ui->lineEditRenamePattern->palette().color(QPalette::Text) != Qt::red)
3745                 {
3746                         MessageBeep(MB_ICONERROR);
3747                         SET_TEXT_COLOR(ui->lineEditRenamePattern, Qt::red);
3748                 }
3749         }
3750         else
3751         {
3752                 if(ui->lineEditRenamePattern->palette().color(QPalette::Text) != Qt::black)
3753                 {
3754                         MessageBeep(MB_ICONINFORMATION);
3755                         SET_TEXT_COLOR(ui->lineEditRenamePattern, Qt::black);
3756                 }
3757         }
3758
3759         ui->labelRanameExample->setText(lamexp_clean_filename(pattern));
3760 }
3761
3762 /*
3763  * Show list of rename macros
3764  */
3765 void MainWindow::showRenameMacros(const QString &text)
3766 {
3767         if(text.compare("reset", Qt::CaseInsensitive) == 0)
3768         {
3769                 ui->lineEditRenamePattern->setText(m_settings->renameOutputFilesPatternDefault());
3770                 return;
3771         }
3772
3773         const QString format = QString("<tr><td><tt>&lt;%1&gt;</tt></td><td>&nbsp;&nbsp;</td><td>%2</td></tr>");
3774
3775         QString message = QString("<table>");
3776         message += QString(format).arg("BaseName", tr("File name without extension"));
3777         message += QString(format).arg("TrackNo", tr("Track number with leading zero"));
3778         message += QString(format).arg("Title", tr("Track title"));
3779         message += QString(format).arg("Artist", tr("Artist name"));
3780         message += QString(format).arg("Album", tr("Album name"));
3781         message += QString(format).arg("Year", tr("Year with (at least) four digits"));
3782         message += QString(format).arg("Comment", tr("Comment"));
3783         message += "</table><br><br>";
3784         message += QString("%1<br>").arg(tr("Characters forbidden in file names:"));
3785         message += "<b><tt>\\ / : * ? &lt; &gt; |<br>";
3786         
3787         QMessageBox::information(this, tr("Rename Macros"), message, tr("Discard"));
3788 }
3789
3790 void MainWindow::forceStereoDownmixEnabledChanged(bool checked)
3791 {
3792         m_settings->forceStereoDownmix(checked);
3793 }
3794
3795 /*
3796  * Maximum number of instances changed
3797  */
3798 void MainWindow::updateMaximumInstances(int value)
3799 {
3800         ui->labelMaxInstances->setText(tr("%1 Instance(s)").arg(QString::number(value)));
3801         m_settings->maximumInstances(ui->checkBoxAutoDetectInstances->isChecked() ? NULL : value);
3802 }
3803
3804 /*
3805  * Auto-detect number of instances
3806  */
3807 void MainWindow::autoDetectInstancesChanged(bool checked)
3808 {
3809         m_settings->maximumInstances(checked ? NULL : ui->sliderMaxInstances->value());
3810 }
3811
3812 /*
3813  * Browse for custom TEMP folder button clicked
3814  */
3815 void MainWindow::browseCustomTempFolderButtonClicked(void)
3816 {
3817         QString newTempFolder;
3818
3819         if(USE_NATIVE_FILE_DIALOG)
3820         {
3821                 newTempFolder = QFileDialog::getExistingDirectory(this, QString(), m_settings->customTempPath());
3822         }
3823         else
3824         {
3825                 QFileDialog dialog(this);
3826                 dialog.setFileMode(QFileDialog::DirectoryOnly);
3827                 dialog.setDirectory(m_settings->customTempPath());
3828                 if(dialog.exec())
3829                 {
3830                         newTempFolder = dialog.selectedFiles().first();
3831                 }
3832         }
3833
3834         if(!newTempFolder.isEmpty())
3835         {
3836                 QFile writeTest(QString("%1/~%2.tmp").arg(newTempFolder, lamexp_rand_str()));
3837                 if(writeTest.open(QIODevice::ReadWrite))
3838                 {
3839                         writeTest.remove();
3840                         ui->lineEditCustomTempFolder->setText(QDir::toNativeSeparators(newTempFolder));
3841                 }
3842                 else
3843                 {
3844                         QMessageBox::warning(this, tr("Access Denied"), tr("Cannot write to the selected directory. Please choose another directory!"));
3845                 }
3846         }
3847 }
3848
3849 /*
3850  * Custom TEMP folder changed
3851  */
3852 void MainWindow::customTempFolderChanged(const QString &text)
3853 {
3854         m_settings->customTempPath(QDir::fromNativeSeparators(text));
3855 }
3856
3857 /*
3858  * Use custom TEMP folder option changed
3859  */
3860 void MainWindow::useCustomTempFolderChanged(bool checked)
3861 {
3862         m_settings->customTempPathEnabled(!checked);
3863 }
3864
3865 /*
3866  * Help for custom parameters was requested
3867  */
3868 void MainWindow::customParamsHelpRequested(QWidget *obj, QEvent *event)
3869 {
3870         if(event->type() != QEvent::MouseButtonRelease)
3871         {
3872                 return;
3873         }
3874
3875         if(QMouseEvent *mouseEvent = dynamic_cast<QMouseEvent*>(event))
3876         {
3877                 QPoint pos = mouseEvent->pos();
3878                 if(!(pos.x() <= obj->width() && pos.y() <= obj->height() && pos.x() >= 0 && pos.y() >= 0 && mouseEvent->button() != Qt::MidButton))
3879                 {
3880                         return;
3881                 }
3882         }
3883
3884         if(obj == ui->helpCustomParamLAME)         showCustomParamsHelpScreen("lame.exe", "--longhelp");
3885         else if(obj == ui->helpCustomParamOggEnc)  showCustomParamsHelpScreen("oggenc2.exe", "--help");
3886         else if(obj == ui->helpCustomParamNeroAAC)
3887         {
3888                 if(m_qaacEncoderAvailable)         showCustomParamsHelpScreen("qaac.exe", "--help");
3889                 else if(m_fhgEncoderAvailable)     showCustomParamsHelpScreen("fhgaacenc.exe", "");
3890                 else if(m_neroEncoderAvailable)    showCustomParamsHelpScreen("neroAacEnc.exe", "-help");
3891                 else MessageBeep(MB_ICONERROR);
3892         }
3893         else if(obj == ui->helpCustomParamFLAC)    showCustomParamsHelpScreen("flac.exe", "--help");
3894         else if(obj == ui->helpCustomParamAften)   showCustomParamsHelpScreen("aften.exe", "-h");
3895         else if(obj == ui->helpCustomParamOpus)    showCustomParamsHelpScreen("opusenc_std.exe", "--help");
3896         else MessageBeep(MB_ICONERROR);
3897 }
3898
3899 /*
3900  * Show help for custom parameters
3901  */
3902 void MainWindow::showCustomParamsHelpScreen(const QString &toolName, const QString &command)
3903 {
3904         const QString binary = lamexp_lookup_tool(toolName);
3905         if(binary.isEmpty())
3906         {
3907                 MessageBeep(MB_ICONERROR);
3908                 qWarning("customParamsHelpRequested: Binary could not be found!");
3909                 return;
3910         }
3911
3912         QProcess *process = new QProcess();
3913         process->setProcessChannelMode(QProcess::MergedChannels);
3914         process->setReadChannel(QProcess::StandardOutput);
3915         process->start(binary, command.isEmpty() ? QStringList() : QStringList() << command);
3916         qApp->setOverrideCursor(QCursor(Qt::WaitCursor));
3917
3918         if(process->waitForStarted(15000))
3919         {
3920                 qApp->processEvents();
3921                 process->waitForFinished(15000);
3922         }
3923         
3924         if(process->state() != QProcess::NotRunning)
3925         {
3926                 process->kill();
3927                 process->waitForFinished(-1);
3928         }
3929
3930         qApp->restoreOverrideCursor();
3931         QStringList output; bool spaceFlag = true;
3932
3933         while(process->canReadLine())
3934         {
3935                 QString temp = QString::fromUtf8(process->readLine());
3936                 TRIM_STRING_RIGHT(temp);
3937                 if(temp.isEmpty())
3938                 {
3939                         if(!spaceFlag) { output << temp; spaceFlag = true; }
3940                 }
3941                 else
3942                 {
3943                         output << temp; spaceFlag = false;
3944                 }
3945         }
3946
3947         LAMEXP_DELETE(process);
3948
3949         if(output.count() < 1)
3950         {
3951                 qWarning("Empty output, cannot show help screen!");
3952                 MessageBeep(MB_ICONERROR);
3953         }
3954
3955         LogViewDialog *dialog = new LogViewDialog(this);
3956         TEMP_HIDE_DROPBOX( dialog->exec(output); );
3957         LAMEXP_DELETE(dialog);
3958 }
3959
3960 void MainWindow::overwriteModeChanged(int id)
3961 {
3962         if((id == SettingsModel::Overwrite_Replaces) && (m_settings->overwriteMode() != SettingsModel::Overwrite_Replaces))
3963         {
3964                 if(QMessageBox::warning(this, tr("Overwrite Mode"), tr("Warning: This mode may overwrite existing files with no way to revert!"), tr("Continue"), tr("Revert"), QString(), 1) != 0)
3965                 {
3966                         ui->radioButtonOverwriteModeKeepBoth->setChecked(m_settings->overwriteMode() == SettingsModel::Overwrite_KeepBoth);
3967                         ui->radioButtonOverwriteModeSkipFile->setChecked(m_settings->overwriteMode() == SettingsModel::Overwrite_SkipFile);
3968                         return;
3969                 }
3970         }
3971
3972         m_settings->overwriteMode(id);
3973 }
3974
3975 /*
3976  * Reset all advanced options to their defaults
3977  */
3978 void MainWindow::resetAdvancedOptionsButtonClicked(void)
3979 {
3980         ui->sliderLameAlgoQuality->setValue(m_settings->lameAlgoQualityDefault());
3981         ui->spinBoxBitrateManagementMin->setValue(m_settings->bitrateManagementMinRateDefault());
3982         ui->spinBoxBitrateManagementMax->setValue(m_settings->bitrateManagementMaxRateDefault());
3983         ui->spinBoxNormalizationFilter->setValue(static_cast<double>(m_settings->normalizationFilterMaxVolumeDefault()) / 100.0);
3984         ui->spinBoxToneAdjustBass->setValue(static_cast<double>(m_settings->toneAdjustBassDefault()) / 100.0);
3985         ui->spinBoxToneAdjustTreble->setValue(static_cast<double>(m_settings->toneAdjustTrebleDefault()) / 100.0);
3986         ui->spinBoxAftenSearchSize->setValue(m_settings->aftenExponentSearchSizeDefault());
3987         ui->spinBoxOpusComplexity->setValue(m_settings->opusComplexityDefault());
3988         ui->comboBoxMP3ChannelMode->setCurrentIndex(m_settings->lameChannelModeDefault());
3989         ui->comboBoxSamplingRate->setCurrentIndex(m_settings->samplingRateDefault());
3990         ui->comboBoxAACProfile->setCurrentIndex(m_settings->aacEncProfileDefault());
3991         ui->comboBoxAftenCodingMode->setCurrentIndex(m_settings->aftenAudioCodingModeDefault());
3992         ui->comboBoxAftenDRCMode->setCurrentIndex(m_settings->aftenDynamicRangeCompressionDefault());
3993         ui->comboBoxNormalizationMode->setCurrentIndex(m_settings->normalizationFilterEqualizationModeDefault());
3994         //comboBoxOpusOptimize->setCurrentIndex(m_settings->opusOptimizeForDefault());
3995         ui->comboBoxOpusFramesize->setCurrentIndex(m_settings->opusFramesizeDefault());
3996         SET_CHECKBOX_STATE(ui->checkBoxBitrateManagement, m_settings->bitrateManagementEnabledDefault());
3997         SET_CHECKBOX_STATE(ui->checkBoxNeroAAC2PassMode, m_settings->neroAACEnable2PassDefault());
3998         SET_CHECKBOX_STATE(ui->checkBoxNormalizationFilter, m_settings->normalizationFilterEnabledDefault());
3999         SET_CHECKBOX_STATE(ui->checkBoxAutoDetectInstances, (m_settings->maximumInstancesDefault() < 1));
4000         SET_CHECKBOX_STATE(ui->checkBoxUseSystemTempFolder, !m_settings->customTempPathEnabledDefault());
4001         SET_CHECKBOX_STATE(ui->checkBoxAftenFastAllocation, m_settings->aftenFastBitAllocationDefault());
4002         SET_CHECKBOX_STATE(ui->checkBoxRenameOutput, m_settings->renameOutputFilesEnabledDefault());
4003         SET_CHECKBOX_STATE(ui->checkBoxForceStereoDownmix, m_settings->forceStereoDownmixDefault());
4004         ui->lineEditCustomParamLAME->setText(m_settings->customParametersLAMEDefault());
4005         ui->lineEditCustomParamOggEnc->setText(m_settings->customParametersOggEncDefault());
4006         ui->lineEditCustomParamNeroAAC->setText(m_settings->customParametersAacEncDefault());
4007         ui->lineEditCustomParamFLAC->setText(m_settings->customParametersFLACDefault());
4008         ui->lineEditCustomParamOpus->setText(m_settings->customParametersFLACDefault());
4009         ui->lineEditCustomTempFolder->setText(QDir::toNativeSeparators(m_settings->customTempPathDefault()));
4010         ui->lineEditRenamePattern->setText(m_settings->renameOutputFilesPatternDefault());
4011         if(m_settings->overwriteModeDefault() == SettingsModel::Overwrite_KeepBoth) ui->radioButtonOverwriteModeKeepBoth->click();
4012         if(m_settings->overwriteModeDefault() == SettingsModel::Overwrite_SkipFile) ui->radioButtonOverwriteModeSkipFile->click();
4013         if(m_settings->overwriteModeDefault() == SettingsModel::Overwrite_Replaces) ui->radioButtonOverwriteModeReplaces->click();
4014         customParamsChanged();
4015         ui->scrollArea->verticalScrollBar()->setValue(0);
4016 }
4017
4018 // =========================================================
4019 // Multi-instance handling slots
4020 // =========================================================
4021
4022 /*
4023  * Other instance detected
4024  */
4025 void MainWindow::notifyOtherInstance(void)
4026 {
4027         if(!m_banner->isVisible())
4028         {
4029                 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);
4030                 msgBox.exec();
4031         }
4032 }
4033
4034 /*
4035  * Add file from another instance
4036  */
4037 void MainWindow::addFileDelayed(const QString &filePath, bool tryASAP)
4038 {
4039         if(tryASAP && !m_delayedFileTimer->isActive())
4040         {
4041                 qDebug("Received file: %s", filePath.toUtf8().constData());
4042                 m_delayedFileList->append(filePath);
4043                 QTimer::singleShot(0, this, SLOT(handleDelayedFiles()));
4044         }
4045         
4046         m_delayedFileTimer->stop();
4047         qDebug("Received file: %s", filePath.toUtf8().constData());
4048         m_delayedFileList->append(filePath);
4049         m_delayedFileTimer->start(5000);
4050 }
4051
4052 /*
4053  * Add files from another instance
4054  */
4055 void MainWindow::addFilesDelayed(const QStringList &filePaths, bool tryASAP)
4056 {
4057         if(tryASAP && !m_delayedFileTimer->isActive())
4058         {
4059                 qDebug("Received %d file(s).", filePaths.count());
4060                 m_delayedFileList->append(filePaths);
4061                 QTimer::singleShot(0, this, SLOT(handleDelayedFiles()));
4062         }
4063         else
4064         {
4065                 m_delayedFileTimer->stop();
4066                 qDebug("Received %d file(s).", filePaths.count());
4067                 m_delayedFileList->append(filePaths);
4068                 m_delayedFileTimer->start(5000);
4069         }
4070 }
4071
4072 /*
4073  * Add folder from another instance
4074  */
4075 void MainWindow::addFolderDelayed(const QString &folderPath, bool recursive)
4076 {
4077         if(!m_banner->isVisible())
4078         {
4079                 addFolder(folderPath, recursive, true);
4080         }
4081 }
4082
4083 // =========================================================
4084 // Misc slots
4085 // =========================================================
4086
4087 /*
4088  * Restore the override cursor
4089  */
4090 void MainWindow::restoreCursor(void)
4091 {
4092         QApplication::restoreOverrideCursor();
4093 }