Updated Ukrainian translation.
[LameXP.git] / src / Dialog_MainWindow.cpp
blob02bd5931d6e8145d600a0a57e94b719e45bd3e4a
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2015 LoRd_MuldeR <MuldeR2@GMX.de>
4 //
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; either version 2 of the License, or
8 // (at your option) any later version, but always including the *additional*
9 // restrictions defined in the "License.txt" file.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License along
17 // with this program; if not, write to the Free Software Foundation, Inc.,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 // http://www.gnu.org/licenses/gpl-2.0.txt
21 ///////////////////////////////////////////////////////////////////////////////
23 #include "Dialog_MainWindow.h"
25 //UIC includes
26 #include "UIC_MainWindow.h"
28 //LameXP includes
29 #include "Global.h"
30 #include "Dialog_WorkingBanner.h"
31 #include "Dialog_MetaInfo.h"
32 #include "Dialog_About.h"
33 #include "Dialog_Update.h"
34 #include "Dialog_DropBox.h"
35 #include "Dialog_CueImport.h"
36 #include "Dialog_LogView.h"
37 #include "Thread_FileAnalyzer.h"
38 #include "Thread_MessageHandler.h"
39 #include "Model_MetaInfo.h"
40 #include "Model_Settings.h"
41 #include "Model_FileList.h"
42 #include "Model_FileSystem.h"
43 #include "Registry_Encoder.h"
44 #include "Registry_Decoder.h"
45 #include "Encoder_Abstract.h"
46 #include "ShellIntegration.h"
47 #include "CustomEventFilter.h"
49 //Mutils includes
50 #include <MUtils/Global.h>
51 #include <MUtils/OSSupport.h>
52 #include <MUtils/GUI.h>
53 #include <MUtils/Exception.h>
54 #include <MUtils/Sound.h>
55 #include <MUtils/Translation.h>
56 #include <MUtils/Version.h>
58 //Qt includes
59 #include <QMessageBox>
60 #include <QTimer>
61 #include <QDesktopWidget>
62 #include <QDate>
63 #include <QFileDialog>
64 #include <QInputDialog>
65 #include <QFileSystemModel>
66 #include <QDesktopServices>
67 #include <QUrl>
68 #include <QPlastiqueStyle>
69 #include <QCleanlooksStyle>
70 #include <QWindowsVistaStyle>
71 #include <QWindowsStyle>
72 #include <QSysInfo>
73 #include <QDragEnterEvent>
74 #include <QMimeData>
75 #include <QProcess>
76 #include <QUuid>
77 #include <QProcessEnvironment>
78 #include <QCryptographicHash>
79 #include <QTranslator>
80 #include <QResource>
81 #include <QScrollBar>
83 ////////////////////////////////////////////////////////////
84 // Helper macros
85 ////////////////////////////////////////////////////////////
87 #define BANNER_VISIBLE ((m_banner != NULL) && m_banner->isVisible())
89 #define INIT_BANNER() do \
90 { \
91 if(m_banner == NULL) \
92 { \
93 m_banner = new WorkingBanner(this); \
94 } \
95 } \
96 while(0)
98 #define SHOW_BANNER(TXT) do \
99 { \
100 INIT_BANNER(); \
101 m_banner->show((TXT)); \
103 while(0)
105 #define SHOW_BANNER_ARG(TXT, ARG) do \
107 INIT_BANNER(); \
108 m_banner->show((TXT), (ARG)); \
110 while(0)
113 #define SHOW_BANNER_CONDITIONALLY(FLAG, TEST, TXT) do \
115 if((!(FLAG)) && ((TEST))) \
117 INIT_BANNER(); \
118 m_banner->show((TXT)); \
119 FLAG = true; \
122 while(0)
124 #define ABORT_IF_BUSY do \
126 if(BANNER_VISIBLE || m_delayedFileTimer->isActive() || (QApplication::activeModalWidget() != NULL)) \
128 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN); \
129 return; \
132 while(0)
134 #define SET_TEXT_COLOR(WIDGET, COLOR) do \
136 QPalette _palette = WIDGET->palette(); \
137 _palette.setColor(QPalette::WindowText, (COLOR)); \
138 _palette.setColor(QPalette::Text, (COLOR)); \
139 WIDGET->setPalette(_palette); \
141 while(0)
143 #define SET_FONT_BOLD(WIDGET,BOLD) do \
145 QFont _font = WIDGET->font(); \
146 _font.setBold(BOLD); \
147 WIDGET->setFont(_font); \
149 while(0)
151 #define TEMP_HIDE_DROPBOX(CMD) do \
153 bool _dropBoxVisible = m_dropBox->isVisible(); \
154 if(_dropBoxVisible) m_dropBox->hide(); \
155 do { CMD } while(0); \
156 if(_dropBoxVisible) m_dropBox->show(); \
158 while(0)
160 #define SET_MODEL(VIEW, MODEL) do \
162 QItemSelectionModel *_tmp = (VIEW)->selectionModel(); \
163 (VIEW)->setModel(MODEL); \
164 MUTILS_DELETE(_tmp); \
166 while(0)
168 #define SET_CHECKBOX_STATE(CHCKBX, STATE) do \
170 if((CHCKBX)->isChecked() != (STATE)) \
172 (CHCKBX)->click(); \
174 if((CHCKBX)->isChecked() != (STATE)) \
176 qWarning("Warning: Failed to set checkbox " #CHCKBX " state!"); \
179 while(0)
181 #define TRIM_STRING_RIGHT(STR) do \
183 while((STR.length() > 0) && STR[STR.length()-1].isSpace()) STR.chop(1); \
185 while(0)
187 #define MAKE_TRANSPARENT(WIDGET, FLAG) do \
189 QPalette _p = (WIDGET)->palette(); \
190 _p.setColor(QPalette::Background, Qt::transparent); \
191 (WIDGET)->setPalette(FLAG ? _p : QPalette()); \
193 while(0)
195 #define WITH_BLOCKED_SIGNALS(WIDGET, CMD, ...) do \
197 const bool _flag = (WIDGET)->blockSignals(true); \
198 (WIDGET)->CMD(__VA_ARGS__); \
199 if(!(_flag)) { (WIDGET)->blockSignals(false); } \
201 while(0)
203 #define PLAY_SOUND_OPTIONAL(NAME, ASYNC) do \
205 if(m_settings->soundsEnabled()) MUtils::Sound::play_sound((NAME), (ASYNC)); \
207 while(0)
209 #define SHOW_CORNER_WIDGET(FLAG) do \
211 if(QWidget *cornerWidget = ui->menubar->cornerWidget()) \
213 cornerWidget->setVisible((FLAG)); \
216 while(0)
218 #define LINK(URL) QString("<a href=\"%1\">%2</a>").arg(URL).arg(QString(URL).replace("-", "&minus;"))
219 #define FSLINK(PATH) QString("<a href=\"file:///%1\">%2</a>").arg(PATH).arg(QString(PATH).replace("-", "&minus;"))
220 #define CENTER_CURRENT_OUTPUT_FOLDER_DELAYED QTimer::singleShot(125, this, SLOT(centerOutputFolderModel()))
222 static const unsigned int IDM_ABOUTBOX = 0xEFF0;
223 static const char *g_hydrogen_audio_url = "http://wiki.hydrogenaud.io/index.php?title=Main_Page";
224 static const char *g_documents_base_url = "http://lamexp.sourceforge.net/doc";
226 ////////////////////////////////////////////////////////////
227 // Constructor
228 ////////////////////////////////////////////////////////////
230 MainWindow::MainWindow(MUtils::IPCChannel *const ipcChannel, FileListModel *const fileListModel, AudioFileModel_MetaInfo *const metaInfo, SettingsModel *const settingsModel, QWidget *const parent)
232 QMainWindow(parent),
233 ui(new Ui::MainWindow),
234 m_fileListModel(fileListModel),
235 m_metaData(metaInfo),
236 m_settings(settingsModel),
237 m_fileSystemModel(NULL),
238 m_banner(NULL),
239 m_accepted(false),
240 m_firstTimeShown(true),
241 m_outputFolderViewCentering(false),
242 m_outputFolderViewInitCounter(0)
244 //Init the dialog, from the .ui file
245 ui->setupUi(this);
246 setWindowFlags(windowFlags() ^ Qt::WindowMaximizeButtonHint);
248 //Create window icon
249 MUtils::GUI::set_window_icon(this, lamexp_app_icon(), true);
251 //Register meta types
252 qRegisterMetaType<AudioFileModel>("AudioFileModel");
254 //Enabled main buttons
255 connect(ui->buttonAbout, SIGNAL(clicked()), this, SLOT(aboutButtonClicked()));
256 connect(ui->buttonStart, SIGNAL(clicked()), this, SLOT(encodeButtonClicked()));
257 connect(ui->buttonQuit, SIGNAL(clicked()), this, SLOT(closeButtonClicked()));
259 //Setup tab widget
260 ui->tabWidget->setCurrentIndex(0);
261 connect(ui->tabWidget, SIGNAL(currentChanged(int)), this, SLOT(tabPageChanged(int)));
263 //Add system menu
264 MUtils::GUI::sysmenu_append(this, IDM_ABOUTBOX, "About...");
266 //Setup corner widget
267 QLabel *cornerWidget = new QLabel(ui->menubar);
268 m_evenFilterCornerWidget = new CustomEventFilter;
269 cornerWidget->setText("N/A");
270 cornerWidget->setFixedHeight(ui->menubar->height());
271 cornerWidget->setCursor(QCursor(Qt::PointingHandCursor));
272 cornerWidget->hide();
273 cornerWidget->installEventFilter(m_evenFilterCornerWidget);
274 connect(m_evenFilterCornerWidget, SIGNAL(eventOccurred(QWidget*, QEvent*)), this, SLOT(cornerWidgetEventOccurred(QWidget*, QEvent*)));
275 ui->menubar->setCornerWidget(cornerWidget);
277 //--------------------------------
278 // Setup "Source" tab
279 //--------------------------------
281 ui->sourceFileView->setModel(m_fileListModel);
282 ui->sourceFileView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
283 ui->sourceFileView->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);
284 ui->sourceFileView->setContextMenuPolicy(Qt::CustomContextMenu);
285 ui->sourceFileView->viewport()->installEventFilter(this);
286 m_dropNoteLabel = new QLabel(ui->sourceFileView);
287 m_dropNoteLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
288 SET_FONT_BOLD(m_dropNoteLabel, true);
289 SET_TEXT_COLOR(m_dropNoteLabel, Qt::darkGray);
290 m_sourceFilesContextMenu = new QMenu();
291 m_showDetailsContextAction = m_sourceFilesContextMenu->addAction(QIcon(":/icons/zoom.png"), "N/A");
292 m_previewContextAction = m_sourceFilesContextMenu->addAction(QIcon(":/icons/sound.png"), "N/A");
293 m_findFileContextAction = m_sourceFilesContextMenu->addAction(QIcon(":/icons/folder_go.png"), "N/A");
294 m_sourceFilesContextMenu->addSeparator();
295 m_exportCsvContextAction = m_sourceFilesContextMenu->addAction(QIcon(":/icons/table_save.png"), "N/A");
296 m_importCsvContextAction = m_sourceFilesContextMenu->addAction(QIcon(":/icons/folder_table.png"), "N/A");
297 SET_FONT_BOLD(m_showDetailsContextAction, true);
299 connect(ui->buttonAddFiles, SIGNAL(clicked()), this, SLOT(addFilesButtonClicked()));
300 connect(ui->buttonRemoveFile, SIGNAL(clicked()), this, SLOT(removeFileButtonClicked()));
301 connect(ui->buttonClearFiles, SIGNAL(clicked()), this, SLOT(clearFilesButtonClicked()));
302 connect(ui->buttonFileUp, SIGNAL(clicked()), this, SLOT(fileUpButtonClicked()));
303 connect(ui->buttonFileDown, SIGNAL(clicked()), this, SLOT(fileDownButtonClicked()));
304 connect(ui->buttonShowDetails, SIGNAL(clicked()), this, SLOT(showDetailsButtonClicked()));
305 connect(m_fileListModel, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(sourceModelChanged()));
306 connect(m_fileListModel, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(sourceModelChanged()));
307 connect(m_fileListModel, SIGNAL(modelReset()), this, SLOT(sourceModelChanged()));
308 connect(ui->sourceFileView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(sourceFilesContextMenu(QPoint)));
309 connect(ui->sourceFileView->verticalScrollBar(), SIGNAL(sliderMoved(int)), this, SLOT(sourceFilesScrollbarMoved(int)));
310 connect(ui->sourceFileView->verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(sourceFilesScrollbarMoved(int)));
311 connect(m_showDetailsContextAction, SIGNAL(triggered(bool)), this, SLOT(showDetailsButtonClicked()));
312 connect(m_previewContextAction, SIGNAL(triggered(bool)), this, SLOT(previewContextActionTriggered()));
313 connect(m_findFileContextAction, SIGNAL(triggered(bool)), this, SLOT(findFileContextActionTriggered()));
314 connect(m_exportCsvContextAction, SIGNAL(triggered(bool)), this, SLOT(exportCsvContextActionTriggered()));
315 connect(m_importCsvContextAction, SIGNAL(triggered(bool)), this, SLOT(importCsvContextActionTriggered()));
317 //--------------------------------
318 // Setup "Output" tab
319 //--------------------------------
321 ui->outputFolderView->setHeaderHidden(true);
322 ui->outputFolderView->setAnimated(false);
323 ui->outputFolderView->setMouseTracking(false);
324 ui->outputFolderView->setContextMenuPolicy(Qt::CustomContextMenu);
325 ui->outputFolderView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
327 m_evenFilterOutputFolderMouse = new CustomEventFilter;
328 ui->outputFoldersGoUpLabel->installEventFilter(m_evenFilterOutputFolderMouse);
329 ui->outputFoldersEditorLabel->installEventFilter(m_evenFilterOutputFolderMouse);
330 ui->outputFoldersFovoritesLabel->installEventFilter(m_evenFilterOutputFolderMouse);
331 ui->outputFolderLabel->installEventFilter(m_evenFilterOutputFolderMouse);
333 m_evenFilterOutputFolderView = new CustomEventFilter;
334 ui->outputFolderView->installEventFilter(m_evenFilterOutputFolderView);
336 SET_CHECKBOX_STATE(ui->saveToSourceFolderCheckBox, m_settings->outputToSourceDir());
337 ui->prependRelativePathCheckBox->setChecked(m_settings->prependRelativeSourcePath());
339 connect(ui->outputFolderView, SIGNAL(clicked(QModelIndex)), this, SLOT(outputFolderViewClicked(QModelIndex)));
340 connect(ui->outputFolderView, SIGNAL(activated(QModelIndex)), this, SLOT(outputFolderViewClicked(QModelIndex)));
341 connect(ui->outputFolderView, SIGNAL(pressed(QModelIndex)), this, SLOT(outputFolderViewClicked(QModelIndex)));
342 connect(ui->outputFolderView, SIGNAL(entered(QModelIndex)), this, SLOT(outputFolderViewMoved(QModelIndex)));
343 connect(ui->outputFolderView, SIGNAL(expanded(QModelIndex)), this, SLOT(outputFolderItemExpanded(QModelIndex)));
344 connect(ui->buttonMakeFolder, SIGNAL(clicked()), this, SLOT(makeFolderButtonClicked()));
345 connect(ui->buttonGotoHome, SIGNAL(clicked()), SLOT(gotoHomeFolderButtonClicked()));
346 connect(ui->buttonGotoDesktop, SIGNAL(clicked()), this, SLOT(gotoDesktopButtonClicked()));
347 connect(ui->buttonGotoMusic, SIGNAL(clicked()), this, SLOT(gotoMusicFolderButtonClicked()));
348 connect(ui->saveToSourceFolderCheckBox, SIGNAL(clicked()), this, SLOT(saveToSourceFolderChanged()));
349 connect(ui->prependRelativePathCheckBox, SIGNAL(clicked()), this, SLOT(prependRelativePathChanged()));
350 connect(ui->outputFolderEdit, SIGNAL(editingFinished()), this, SLOT(outputFolderEditFinished()));
351 connect(m_evenFilterOutputFolderMouse, SIGNAL(eventOccurred(QWidget*, QEvent*)), this, SLOT(outputFolderMouseEventOccurred(QWidget*, QEvent*)));
352 connect(m_evenFilterOutputFolderView, SIGNAL(eventOccurred(QWidget*, QEvent*)), this, SLOT(outputFolderViewEventOccurred(QWidget*, QEvent*)));
354 if(m_outputFolderContextMenu = new QMenu())
356 m_showFolderContextAction = m_outputFolderContextMenu->addAction(QIcon(":/icons/zoom.png"), "N/A");
357 m_goUpFolderContextAction = m_outputFolderContextMenu->addAction(QIcon(":/icons/folder_up.png"), "N/A");
358 m_outputFolderContextMenu->addSeparator();
359 m_refreshFolderContextAction = m_outputFolderContextMenu->addAction(QIcon(":/icons/arrow_refresh.png"), "N/A");
360 m_outputFolderContextMenu->setDefaultAction(m_showFolderContextAction);
361 connect(ui->outputFolderView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(outputFolderContextMenu(QPoint)));
362 connect(m_showFolderContextAction, SIGNAL(triggered(bool)), this, SLOT(showFolderContextActionTriggered()));
363 connect(m_refreshFolderContextAction, SIGNAL(triggered(bool)), this, SLOT(refreshFolderContextActionTriggered()));
364 connect(m_goUpFolderContextAction, SIGNAL(triggered(bool)), this, SLOT(goUpFolderContextActionTriggered()));
367 if(m_outputFolderFavoritesMenu = new QMenu())
369 m_addFavoriteFolderAction = m_outputFolderFavoritesMenu->addAction(QIcon(":/icons/add.png"), "N/A");
370 m_outputFolderFavoritesMenu->insertSeparator(m_addFavoriteFolderAction);
371 connect(m_addFavoriteFolderAction, SIGNAL(triggered(bool)), this, SLOT(addFavoriteFolderActionTriggered()));
374 ui->outputFolderEdit->setVisible(false);
375 if(m_outputFolderNoteBox = new QLabel(ui->outputFolderView))
377 m_outputFolderNoteBox->setAutoFillBackground(true);
378 m_outputFolderNoteBox->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
379 m_outputFolderNoteBox->setFrameShape(QFrame::StyledPanel);
380 SET_FONT_BOLD(m_outputFolderNoteBox, true);
381 m_outputFolderNoteBox->hide();
385 outputFolderViewClicked(QModelIndex());
386 refreshFavorites();
388 //--------------------------------
389 // Setup "Meta Data" tab
390 //--------------------------------
392 m_metaInfoModel = new MetaInfoModel(m_metaData);
393 m_metaInfoModel->clearData();
394 m_metaInfoModel->setData(m_metaInfoModel->index(4, 1), m_settings->metaInfoPosition());
395 ui->metaDataView->setModel(m_metaInfoModel);
396 ui->metaDataView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
397 ui->metaDataView->verticalHeader()->hide();
398 ui->metaDataView->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);
399 SET_CHECKBOX_STATE(ui->writeMetaDataCheckBox, m_settings->writeMetaTags());
400 ui->generatePlaylistCheckBox->setChecked(m_settings->createPlaylist());
401 connect(ui->buttonEditMeta, SIGNAL(clicked()), this, SLOT(editMetaButtonClicked()));
402 connect(ui->buttonClearMeta, SIGNAL(clicked()), this, SLOT(clearMetaButtonClicked()));
403 connect(ui->writeMetaDataCheckBox, SIGNAL(clicked()), this, SLOT(metaTagsEnabledChanged()));
404 connect(ui->generatePlaylistCheckBox, SIGNAL(clicked()), this, SLOT(playlistEnabledChanged()));
406 //--------------------------------
407 //Setup "Compression" tab
408 //--------------------------------
410 m_encoderButtonGroup = new QButtonGroup(this);
411 m_encoderButtonGroup->addButton(ui->radioButtonEncoderMP3, SettingsModel::MP3Encoder);
412 m_encoderButtonGroup->addButton(ui->radioButtonEncoderVorbis, SettingsModel::VorbisEncoder);
413 m_encoderButtonGroup->addButton(ui->radioButtonEncoderAAC, SettingsModel::AACEncoder);
414 m_encoderButtonGroup->addButton(ui->radioButtonEncoderAC3, SettingsModel::AC3Encoder);
415 m_encoderButtonGroup->addButton(ui->radioButtonEncoderFLAC, SettingsModel::FLACEncoder);
416 m_encoderButtonGroup->addButton(ui->radioButtonEncoderAPE, SettingsModel::MACEncoder);
417 m_encoderButtonGroup->addButton(ui->radioButtonEncoderOpus, SettingsModel::OpusEncoder);
418 m_encoderButtonGroup->addButton(ui->radioButtonEncoderDCA, SettingsModel::DCAEncoder);
419 m_encoderButtonGroup->addButton(ui->radioButtonEncoderPCM, SettingsModel::PCMEncoder);
421 const int aacEncoder = EncoderRegistry::getAacEncoder();
422 ui->radioButtonEncoderAAC->setEnabled(aacEncoder > SettingsModel::AAC_ENCODER_NONE);
424 m_modeButtonGroup = new QButtonGroup(this);
425 m_modeButtonGroup->addButton(ui->radioButtonModeQuality, SettingsModel::VBRMode);
426 m_modeButtonGroup->addButton(ui->radioButtonModeAverageBitrate, SettingsModel::ABRMode);
427 m_modeButtonGroup->addButton(ui->radioButtonConstBitrate, SettingsModel::CBRMode);
429 ui->radioButtonEncoderMP3->setChecked(true);
430 foreach(QAbstractButton *currentButton, m_encoderButtonGroup->buttons())
432 if(currentButton->isEnabled() && (m_encoderButtonGroup->id(currentButton) == m_settings->compressionEncoder()))
434 currentButton->setChecked(true);
435 break;
439 m_evenFilterCompressionTab = new CustomEventFilter();
440 ui->labelCompressionHelp->installEventFilter(m_evenFilterCompressionTab);
441 ui->labelResetEncoders ->installEventFilter(m_evenFilterCompressionTab);
443 connect(m_encoderButtonGroup, SIGNAL(buttonClicked(int)), this, SLOT(updateEncoder(int)));
444 connect(m_modeButtonGroup, SIGNAL(buttonClicked(int)), this, SLOT(updateRCMode(int)));
445 connect(m_evenFilterCompressionTab, SIGNAL(eventOccurred(QWidget*, QEvent*)), this, SLOT(compressionTabEventOccurred(QWidget*, QEvent*)));
446 connect(ui->sliderBitrate, SIGNAL(valueChanged(int)), this, SLOT(updateBitrate(int)));
448 updateEncoder(m_encoderButtonGroup->checkedId());
450 //--------------------------------
451 //Setup "Advanced Options" tab
452 //--------------------------------
454 ui->sliderLameAlgoQuality->setValue(m_settings->lameAlgoQuality());
455 if(m_settings->maximumInstances() > 0) ui->sliderMaxInstances->setValue(m_settings->maximumInstances());
457 ui->spinBoxBitrateManagementMin->setValue(m_settings->bitrateManagementMinRate());
458 ui->spinBoxBitrateManagementMax->setValue(m_settings->bitrateManagementMaxRate());
459 ui->spinBoxNormalizationFilter->setValue(static_cast<double>(m_settings->normalizationFilterMaxVolume()) / 100.0);
460 ui->spinBoxToneAdjustBass->setValue(static_cast<double>(m_settings->toneAdjustBass()) / 100.0);
461 ui->spinBoxToneAdjustTreble->setValue(static_cast<double>(m_settings->toneAdjustTreble()) / 100.0);
462 ui->spinBoxAftenSearchSize->setValue(m_settings->aftenExponentSearchSize());
463 ui->spinBoxOpusComplexity->setValue(m_settings->opusComplexity());
465 ui->comboBoxMP3ChannelMode->setCurrentIndex(m_settings->lameChannelMode());
466 ui->comboBoxSamplingRate->setCurrentIndex(m_settings->samplingRate());
467 ui->comboBoxAACProfile->setCurrentIndex(m_settings->aacEncProfile());
468 ui->comboBoxAftenCodingMode->setCurrentIndex(m_settings->aftenAudioCodingMode());
469 ui->comboBoxAftenDRCMode->setCurrentIndex(m_settings->aftenDynamicRangeCompression());
470 ui->comboBoxNormalizationMode->setCurrentIndex(m_settings->normalizationFilterEQMode());
471 ui->comboBoxOpusFramesize->setCurrentIndex(m_settings->opusFramesize());
473 SET_CHECKBOX_STATE(ui->checkBoxBitrateManagement, m_settings->bitrateManagementEnabled());
474 SET_CHECKBOX_STATE(ui->checkBoxNeroAAC2PassMode, m_settings->neroAACEnable2Pass());
475 SET_CHECKBOX_STATE(ui->checkBoxAftenFastAllocation, m_settings->aftenFastBitAllocation());
476 SET_CHECKBOX_STATE(ui->checkBoxNormalizationFilter, m_settings->normalizationFilterEnabled());
477 SET_CHECKBOX_STATE(ui->checkBoxAutoDetectInstances, (m_settings->maximumInstances() < 1));
478 SET_CHECKBOX_STATE(ui->checkBoxUseSystemTempFolder, !m_settings->customTempPathEnabled());
479 SET_CHECKBOX_STATE(ui->checkBoxRenameOutput, m_settings->renameOutputFilesEnabled());
480 SET_CHECKBOX_STATE(ui->checkBoxForceStereoDownmix, m_settings->forceStereoDownmix());
481 SET_CHECKBOX_STATE(ui->checkBoxOpusDisableResample, m_settings->opusDisableResample());
482 ui->checkBoxNeroAAC2PassMode->setEnabled(aacEncoder == SettingsModel::AAC_ENCODER_NERO);
484 ui->lineEditCustomParamLAME ->setText(EncoderRegistry::loadEncoderCustomParams(m_settings, SettingsModel::MP3Encoder));
485 ui->lineEditCustomParamOggEnc ->setText(EncoderRegistry::loadEncoderCustomParams(m_settings, SettingsModel::VorbisEncoder));
486 ui->lineEditCustomParamNeroAAC->setText(EncoderRegistry::loadEncoderCustomParams(m_settings, SettingsModel::AACEncoder));
487 ui->lineEditCustomParamFLAC ->setText(EncoderRegistry::loadEncoderCustomParams(m_settings, SettingsModel::FLACEncoder));
488 ui->lineEditCustomParamAften ->setText(EncoderRegistry::loadEncoderCustomParams(m_settings, SettingsModel::AC3Encoder));
489 ui->lineEditCustomParamOpus ->setText(EncoderRegistry::loadEncoderCustomParams(m_settings, SettingsModel::OpusEncoder));
490 ui->lineEditCustomTempFolder ->setText(QDir::toNativeSeparators(m_settings->customTempPath()));
491 ui->lineEditRenamePattern ->setText(m_settings->renameOutputFilesPattern());
493 m_evenFilterCustumParamsHelp = new CustomEventFilter();
494 ui->helpCustomParamLAME->installEventFilter(m_evenFilterCustumParamsHelp);
495 ui->helpCustomParamOggEnc->installEventFilter(m_evenFilterCustumParamsHelp);
496 ui->helpCustomParamNeroAAC->installEventFilter(m_evenFilterCustumParamsHelp);
497 ui->helpCustomParamFLAC->installEventFilter(m_evenFilterCustumParamsHelp);
498 ui->helpCustomParamAften->installEventFilter(m_evenFilterCustumParamsHelp);
499 ui->helpCustomParamOpus->installEventFilter(m_evenFilterCustumParamsHelp);
501 m_overwriteButtonGroup = new QButtonGroup(this);
502 m_overwriteButtonGroup->addButton(ui->radioButtonOverwriteModeKeepBoth, SettingsModel::Overwrite_KeepBoth);
503 m_overwriteButtonGroup->addButton(ui->radioButtonOverwriteModeSkipFile, SettingsModel::Overwrite_SkipFile);
504 m_overwriteButtonGroup->addButton(ui->radioButtonOverwriteModeReplaces, SettingsModel::Overwrite_Replaces);
506 ui->radioButtonOverwriteModeKeepBoth->setChecked(m_settings->overwriteMode() == SettingsModel::Overwrite_KeepBoth);
507 ui->radioButtonOverwriteModeSkipFile->setChecked(m_settings->overwriteMode() == SettingsModel::Overwrite_SkipFile);
508 ui->radioButtonOverwriteModeReplaces->setChecked(m_settings->overwriteMode() == SettingsModel::Overwrite_Replaces);
510 connect(ui->sliderLameAlgoQuality, SIGNAL(valueChanged(int)), this, SLOT(updateLameAlgoQuality(int)));
511 connect(ui->checkBoxBitrateManagement, SIGNAL(clicked(bool)), this, SLOT(bitrateManagementEnabledChanged(bool)));
512 connect(ui->spinBoxBitrateManagementMin, SIGNAL(valueChanged(int)), this, SLOT(bitrateManagementMinChanged(int)));
513 connect(ui->spinBoxBitrateManagementMax, SIGNAL(valueChanged(int)), this, SLOT(bitrateManagementMaxChanged(int)));
514 connect(ui->comboBoxMP3ChannelMode, SIGNAL(currentIndexChanged(int)), this, SLOT(channelModeChanged(int)));
515 connect(ui->comboBoxSamplingRate, SIGNAL(currentIndexChanged(int)), this, SLOT(samplingRateChanged(int)));
516 connect(ui->checkBoxNeroAAC2PassMode, SIGNAL(clicked(bool)), this, SLOT(neroAAC2PassChanged(bool)));
517 connect(ui->comboBoxAACProfile, SIGNAL(currentIndexChanged(int)), this, SLOT(neroAACProfileChanged(int)));
518 connect(ui->checkBoxNormalizationFilter, SIGNAL(clicked(bool)), this, SLOT(normalizationEnabledChanged(bool)));
519 connect(ui->comboBoxAftenCodingMode, SIGNAL(currentIndexChanged(int)), this, SLOT(aftenCodingModeChanged(int)));
520 connect(ui->comboBoxAftenDRCMode, SIGNAL(currentIndexChanged(int)), this, SLOT(aftenDRCModeChanged(int)));
521 connect(ui->spinBoxAftenSearchSize, SIGNAL(valueChanged(int)), this, SLOT(aftenSearchSizeChanged(int)));
522 connect(ui->checkBoxAftenFastAllocation, SIGNAL(clicked(bool)), this, SLOT(aftenFastAllocationChanged(bool)));
523 connect(ui->spinBoxNormalizationFilter, SIGNAL(valueChanged(double)), this, SLOT(normalizationMaxVolumeChanged(double)));
524 connect(ui->comboBoxNormalizationMode, SIGNAL(currentIndexChanged(int)), this, SLOT(normalizationModeChanged(int)));
525 connect(ui->spinBoxToneAdjustBass, SIGNAL(valueChanged(double)), this, SLOT(toneAdjustBassChanged(double)));
526 connect(ui->spinBoxToneAdjustTreble, SIGNAL(valueChanged(double)), this, SLOT(toneAdjustTrebleChanged(double)));
527 connect(ui->buttonToneAdjustReset, SIGNAL(clicked()), this, SLOT(toneAdjustTrebleReset()));
528 connect(ui->lineEditCustomParamLAME, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
529 connect(ui->lineEditCustomParamOggEnc, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
530 connect(ui->lineEditCustomParamNeroAAC, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
531 connect(ui->lineEditCustomParamFLAC, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
532 connect(ui->lineEditCustomParamAften, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
533 connect(ui->lineEditCustomParamOpus, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
534 connect(ui->sliderMaxInstances, SIGNAL(valueChanged(int)), this, SLOT(updateMaximumInstances(int)));
535 connect(ui->checkBoxAutoDetectInstances, SIGNAL(clicked(bool)), this, SLOT(autoDetectInstancesChanged(bool)));
536 connect(ui->buttonBrowseCustomTempFolder, SIGNAL(clicked()), this, SLOT(browseCustomTempFolderButtonClicked()));
537 connect(ui->lineEditCustomTempFolder, SIGNAL(textChanged(QString)), this, SLOT(customTempFolderChanged(QString)));
538 connect(ui->checkBoxUseSystemTempFolder, SIGNAL(clicked(bool)), this, SLOT(useCustomTempFolderChanged(bool)));
539 connect(ui->buttonResetAdvancedOptions, SIGNAL(clicked()), this, SLOT(resetAdvancedOptionsButtonClicked()));
540 connect(ui->checkBoxRenameOutput, SIGNAL(clicked(bool)), this, SLOT(renameOutputEnabledChanged(bool)));
541 connect(ui->lineEditRenamePattern, SIGNAL(editingFinished()), this, SLOT(renameOutputPatternChanged()));
542 connect(ui->lineEditRenamePattern, SIGNAL(textChanged(QString)), this, SLOT(renameOutputPatternChanged(QString)));
543 connect(ui->labelShowRenameMacros, SIGNAL(linkActivated(QString)), this, SLOT(showRenameMacros(QString)));
544 connect(ui->checkBoxForceStereoDownmix, SIGNAL(clicked(bool)), this, SLOT(forceStereoDownmixEnabledChanged(bool)));
545 connect(ui->comboBoxOpusFramesize, SIGNAL(currentIndexChanged(int)), this, SLOT(opusSettingsChanged()));
546 connect(ui->spinBoxOpusComplexity, SIGNAL(valueChanged(int)), this, SLOT(opusSettingsChanged()));
547 connect(ui->checkBoxOpusDisableResample, SIGNAL(clicked(bool)), SLOT(opusSettingsChanged()));
548 connect(m_overwriteButtonGroup, SIGNAL(buttonClicked(int)), this, SLOT(overwriteModeChanged(int)));
549 connect(m_evenFilterCustumParamsHelp, SIGNAL(eventOccurred(QWidget*, QEvent*)), this, SLOT(customParamsHelpRequested(QWidget*, QEvent*)));
551 //--------------------------------
552 // Force initial GUI update
553 //--------------------------------
555 updateLameAlgoQuality(ui->sliderLameAlgoQuality->value());
556 updateMaximumInstances(ui->sliderMaxInstances->value());
557 toneAdjustTrebleChanged(ui->spinBoxToneAdjustTreble->value());
558 toneAdjustBassChanged(ui->spinBoxToneAdjustBass->value());
559 customParamsChanged();
561 //--------------------------------
562 // Initialize actions
563 //--------------------------------
565 //Activate file menu actions
566 ui->actionOpenFolder->setData(QVariant::fromValue<bool>(false));
567 ui->actionOpenFolderRecursively->setData(QVariant::fromValue<bool>(true));
568 connect(ui->actionOpenFolder, SIGNAL(triggered()), this, SLOT(openFolderActionActivated()));
569 connect(ui->actionOpenFolderRecursively, SIGNAL(triggered()), this, SLOT(openFolderActionActivated()));
571 //Activate view menu actions
572 m_tabActionGroup = new QActionGroup(this);
573 m_tabActionGroup->addAction(ui->actionSourceFiles);
574 m_tabActionGroup->addAction(ui->actionOutputDirectory);
575 m_tabActionGroup->addAction(ui->actionCompression);
576 m_tabActionGroup->addAction(ui->actionMetaData);
577 m_tabActionGroup->addAction(ui->actionAdvancedOptions);
578 ui->actionSourceFiles->setData(0);
579 ui->actionOutputDirectory->setData(1);
580 ui->actionMetaData->setData(2);
581 ui->actionCompression->setData(3);
582 ui->actionAdvancedOptions->setData(4);
583 ui->actionSourceFiles->setChecked(true);
584 connect(m_tabActionGroup, SIGNAL(triggered(QAction*)), this, SLOT(tabActionActivated(QAction*)));
586 //Activate style menu actions
587 m_styleActionGroup = new QActionGroup(this);
588 m_styleActionGroup->addAction(ui->actionStylePlastique);
589 m_styleActionGroup->addAction(ui->actionStyleCleanlooks);
590 m_styleActionGroup->addAction(ui->actionStyleWindowsVista);
591 m_styleActionGroup->addAction(ui->actionStyleWindowsXP);
592 m_styleActionGroup->addAction(ui->actionStyleWindowsClassic);
593 ui->actionStylePlastique->setData(0);
594 ui->actionStyleCleanlooks->setData(1);
595 ui->actionStyleWindowsVista->setData(2);
596 ui->actionStyleWindowsXP->setData(3);
597 ui->actionStyleWindowsClassic->setData(4);
598 ui->actionStylePlastique->setChecked(true);
599 ui->actionStyleWindowsXP->setEnabled((QSysInfo::windowsVersion() & QSysInfo::WV_NT_based) >= QSysInfo::WV_XP && MUtils::GUI::themes_enabled());
600 ui->actionStyleWindowsVista->setEnabled((QSysInfo::windowsVersion() & QSysInfo::WV_NT_based) >= QSysInfo::WV_VISTA && MUtils::GUI::themes_enabled());
601 connect(m_styleActionGroup, SIGNAL(triggered(QAction*)), this, SLOT(styleActionActivated(QAction*)));
602 styleActionActivated(NULL);
604 //Populate the language menu
605 m_languageActionGroup = new QActionGroup(this);
606 QStringList translations;
607 if(MUtils::Translation::enumerate(translations) > 0)
609 for(QStringList::ConstIterator iter = translations.constBegin(); iter != translations.constEnd(); iter++)
611 QAction *currentLanguage = new QAction(this);
612 currentLanguage->setData(*iter);
613 currentLanguage->setText(MUtils::Translation::get_name(*iter));
614 currentLanguage->setIcon(QIcon(QString(":/flags/%1.png").arg(*iter)));
615 currentLanguage->setCheckable(true);
616 currentLanguage->setChecked(false);
617 m_languageActionGroup->addAction(currentLanguage);
618 ui->menuLanguage->insertAction(ui->actionLoadTranslationFromFile, currentLanguage);
621 ui->menuLanguage->insertSeparator(ui->actionLoadTranslationFromFile);
622 connect(ui->actionLoadTranslationFromFile, SIGNAL(triggered(bool)), this, SLOT(languageFromFileActionActivated(bool)));
623 connect(m_languageActionGroup, SIGNAL(triggered(QAction*)), this, SLOT(languageActionActivated(QAction*)));
624 ui->actionLoadTranslationFromFile->setChecked(false);
626 //Activate tools menu actions
627 ui->actionDisableUpdateReminder->setChecked(!m_settings->autoUpdateEnabled());
628 ui->actionDisableSounds->setChecked(!m_settings->soundsEnabled());
629 ui->actionDisableNeroAacNotifications->setChecked(!m_settings->neroAacNotificationsEnabled());
630 ui->actionDisableSlowStartupNotifications->setChecked(!m_settings->antivirNotificationsEnabled());
631 ui->actionDisableShellIntegration->setChecked(!m_settings->shellIntegrationEnabled());
632 ui->actionDisableShellIntegration->setDisabled(lamexp_version_portable() && ui->actionDisableShellIntegration->isChecked());
633 ui->actionCheckForBetaUpdates->setChecked(m_settings->autoUpdateCheckBeta() || lamexp_version_demo());
634 ui->actionCheckForBetaUpdates->setEnabled(!lamexp_version_demo());
635 ui->actionHibernateComputer->setChecked(m_settings->hibernateComputer());
636 ui->actionHibernateComputer->setEnabled(MUtils::OS::is_hibernation_supported());
637 connect(ui->actionDisableUpdateReminder, SIGNAL(triggered(bool)), this, SLOT(disableUpdateReminderActionTriggered(bool)));
638 connect(ui->actionDisableSounds, SIGNAL(triggered(bool)), this, SLOT(disableSoundsActionTriggered(bool)));
639 connect(ui->actionDisableNeroAacNotifications, SIGNAL(triggered(bool)), this, SLOT(disableNeroAacNotificationsActionTriggered(bool)));
640 connect(ui->actionDisableSlowStartupNotifications, SIGNAL(triggered(bool)), this, SLOT(disableSlowStartupNotificationsActionTriggered(bool)));
641 connect(ui->actionDisableShellIntegration, SIGNAL(triggered(bool)), this, SLOT(disableShellIntegrationActionTriggered(bool)));
642 connect(ui->actionShowDropBoxWidget, SIGNAL(triggered(bool)), this, SLOT(showDropBoxWidgetActionTriggered(bool)));
643 connect(ui->actionHibernateComputer, SIGNAL(triggered(bool)), this, SLOT(hibernateComputerActionTriggered(bool)));
644 connect(ui->actionCheckForBetaUpdates, SIGNAL(triggered(bool)), this, SLOT(checkForBetaUpdatesActionTriggered(bool)));
645 connect(ui->actionImportCueSheet, SIGNAL(triggered(bool)), this, SLOT(importCueSheetActionTriggered(bool)));
647 //Activate help menu actions
648 ui->actionVisitHomepage ->setData(QString::fromLatin1(lamexp_website_url()));
649 ui->actionVisitSupport ->setData(QString::fromLatin1(lamexp_support_url()));
650 ui->actionVisitMuldersSite ->setData(QString::fromLatin1(lamexp_mulders_url()));
651 ui->actionVisitTracker ->setData(QString::fromLatin1(lamexp_tracker_url()));
652 ui->actionVisitHAK ->setData(QString::fromLatin1(g_hydrogen_audio_url));
653 ui->actionDocumentManual ->setData(QString("%1/Manual.html") .arg(QApplication::applicationDirPath()));
654 ui->actionDocumentChangelog->setData(QString("%1/Changelog.html").arg(QApplication::applicationDirPath()));
655 ui->actionDocumentTranslate->setData(QString("%1/Translate.html").arg(QApplication::applicationDirPath()));
656 connect(ui->actionCheckUpdates, SIGNAL(triggered()), this, SLOT(checkUpdatesActionActivated()));
657 connect(ui->actionVisitSupport, SIGNAL(triggered()), this, SLOT(visitHomepageActionActivated()));
658 connect(ui->actionVisitTracker, SIGNAL(triggered()), this, SLOT(visitHomepageActionActivated()));
659 connect(ui->actionVisitHomepage, SIGNAL(triggered()), this, SLOT(visitHomepageActionActivated()));
660 connect(ui->actionVisitMuldersSite, SIGNAL(triggered()), this, SLOT(visitHomepageActionActivated()));
661 connect(ui->actionVisitHAK, SIGNAL(triggered()), this, SLOT(visitHomepageActionActivated()));
662 connect(ui->actionDocumentManual, SIGNAL(triggered()), this, SLOT(documentActionActivated()));
663 connect(ui->actionDocumentChangelog, SIGNAL(triggered()), this, SLOT(documentActionActivated()));
664 connect(ui->actionDocumentTranslate, SIGNAL(triggered()), this, SLOT(documentActionActivated()));
666 //--------------------------------
667 // Prepare to show window
668 //--------------------------------
670 //Center window in screen
671 QRect desktopRect = QApplication::desktop()->screenGeometry();
672 QRect thisRect = this->geometry();
673 move((desktopRect.width() - thisRect.width()) / 2, (desktopRect.height() - thisRect.height()) / 2);
674 setMinimumSize(thisRect.width(), thisRect.height());
676 //Create DropBox widget
677 m_dropBox = new DropBox(this, m_fileListModel, m_settings);
678 connect(m_fileListModel, SIGNAL(modelReset()), m_dropBox, SLOT(modelChanged()));
679 connect(m_fileListModel, SIGNAL(rowsInserted(QModelIndex,int,int)), m_dropBox, SLOT(modelChanged()));
680 connect(m_fileListModel, SIGNAL(rowsRemoved(QModelIndex,int,int)), m_dropBox, SLOT(modelChanged()));
681 connect(m_fileListModel, SIGNAL(rowAppended()), m_dropBox, SLOT(modelChanged()));
683 //Create message handler thread
684 m_messageHandler = new MessageHandlerThread(ipcChannel);
685 connect(m_messageHandler, SIGNAL(otherInstanceDetected()), this, SLOT(notifyOtherInstance()), Qt::QueuedConnection);
686 connect(m_messageHandler, SIGNAL(fileReceived(QString)), this, SLOT(addFileDelayed(QString)), Qt::QueuedConnection);
687 connect(m_messageHandler, SIGNAL(folderReceived(QString, bool)), this, SLOT(addFolderDelayed(QString, bool)), Qt::QueuedConnection);
688 connect(m_messageHandler, SIGNAL(killSignalReceived()), this, SLOT(close()), Qt::QueuedConnection);
689 m_messageHandler->start();
691 //Init delayed file handling
692 m_delayedFileList = new QStringList();
693 m_delayedFileTimer = new QTimer();
694 m_delayedFileTimer->setSingleShot(true);
695 m_delayedFileTimer->setInterval(5000);
696 connect(m_delayedFileTimer, SIGNAL(timeout()), this, SLOT(handleDelayedFiles()));
698 //Load translation
699 initializeTranslation();
701 //Re-translate (make sure we translate once)
702 QEvent languageChangeEvent(QEvent::LanguageChange);
703 changeEvent(&languageChangeEvent);
705 //Enable Drag & Drop
706 m_droppedFileList = new QList<QUrl>();
707 this->setAcceptDrops(true);
710 ////////////////////////////////////////////////////////////
711 // Destructor
712 ////////////////////////////////////////////////////////////
714 MainWindow::~MainWindow(void)
716 //Stop message handler thread
717 if(m_messageHandler && m_messageHandler->isRunning())
719 m_messageHandler->stop();
720 if(!m_messageHandler->wait(2500))
722 m_messageHandler->terminate();
723 m_messageHandler->wait();
727 //Unset models
728 SET_MODEL(ui->sourceFileView, NULL);
729 SET_MODEL(ui->outputFolderView, NULL);
730 SET_MODEL(ui->metaDataView, NULL);
732 //Free memory
733 MUTILS_DELETE(m_tabActionGroup);
734 MUTILS_DELETE(m_styleActionGroup);
735 MUTILS_DELETE(m_languageActionGroup);
736 MUTILS_DELETE(m_banner);
737 MUTILS_DELETE(m_fileSystemModel);
738 MUTILS_DELETE(m_messageHandler);
739 MUTILS_DELETE(m_droppedFileList);
740 MUTILS_DELETE(m_delayedFileList);
741 MUTILS_DELETE(m_delayedFileTimer);
742 MUTILS_DELETE(m_metaInfoModel);
743 MUTILS_DELETE(m_encoderButtonGroup);
744 MUTILS_DELETE(m_modeButtonGroup);
745 MUTILS_DELETE(m_overwriteButtonGroup);
746 MUTILS_DELETE(m_sourceFilesContextMenu);
747 MUTILS_DELETE(m_outputFolderFavoritesMenu);
748 MUTILS_DELETE(m_outputFolderContextMenu);
749 MUTILS_DELETE(m_dropBox);
750 MUTILS_DELETE(m_evenFilterCornerWidget);
751 MUTILS_DELETE(m_evenFilterCustumParamsHelp);
752 MUTILS_DELETE(m_evenFilterOutputFolderMouse);
753 MUTILS_DELETE(m_evenFilterOutputFolderView);
754 MUTILS_DELETE(m_evenFilterCompressionTab);
756 //Un-initialize the dialog
757 MUTILS_DELETE(ui);
760 ////////////////////////////////////////////////////////////
761 // PRIVATE FUNCTIONS
762 ////////////////////////////////////////////////////////////
765 * Add file to source list
767 void MainWindow::addFiles(const QStringList &files)
769 if(files.isEmpty())
771 return;
774 WITH_BLOCKED_SIGNALS(ui->tabWidget, setCurrentIndex, 0);
775 tabPageChanged(ui->tabWidget->currentIndex(), true);
777 INIT_BANNER();
778 FileAnalyzer *analyzer = new FileAnalyzer(files);
780 connect(analyzer, SIGNAL(fileSelected(QString)), m_banner, SLOT(setText(QString)), Qt::QueuedConnection);
781 connect(analyzer, SIGNAL(progressValChanged(unsigned int)), m_banner, SLOT(setProgressVal(unsigned int)), Qt::QueuedConnection);
782 connect(analyzer, SIGNAL(progressMaxChanged(unsigned int)), m_banner, SLOT(setProgressMax(unsigned int)), Qt::QueuedConnection);
783 connect(analyzer, SIGNAL(fileAnalyzed(AudioFileModel)), m_fileListModel, SLOT(addFile(AudioFileModel)), Qt::QueuedConnection);
784 connect(m_banner, SIGNAL(userAbort()), analyzer, SLOT(abortProcess()), Qt::DirectConnection);
788 m_fileListModel->setBlockUpdates(true);
789 QTime startTime = QTime::currentTime();
790 m_banner->show(tr("Adding file(s), please wait..."), analyzer);
792 catch(...)
794 /* ignore any exceptions that may occur */
797 m_fileListModel->setBlockUpdates(false);
798 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
799 ui->sourceFileView->update();
800 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
801 ui->sourceFileView->scrollToBottom();
802 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
804 if(analyzer->filesDenied())
806 QMessageBox::warning(this, tr("Access Denied"), QString("%1<br>%2").arg(NOBR(tr("%n file(s) have been rejected, because read access was not granted!", "", analyzer->filesDenied())), NOBR(tr("This usually means the file is locked by another process."))));
808 if(analyzer->filesDummyCDDA())
810 QMessageBox::warning(this, tr("CDDA Files"), QString("%1<br><br>%2<br>%3").arg(NOBR(tr("%n file(s) have been rejected, because they are dummy CDDA files!", "", analyzer->filesDummyCDDA())), NOBR(tr("Sorry, LameXP cannot extract audio tracks from an Audio-CD at present.")), NOBR(tr("We recommend using %1 for that purpose.").arg("<a href=\"http://www.exactaudiocopy.de/\">Exact Audio Copy</a>"))));
812 if(analyzer->filesCueSheet())
814 QMessageBox::warning(this, tr("Cue Sheet"), QString("%1<br>%2").arg(NOBR(tr("%n file(s) have been rejected, because they appear to be Cue Sheet images!", "",analyzer->filesCueSheet())), NOBR(tr("Please use LameXP's Cue Sheet wizard for importing Cue Sheet files."))));
816 if(analyzer->filesRejected())
818 QMessageBox::warning(this, tr("Files Rejected"), QString("%1<br>%2").arg(NOBR(tr("%n file(s) have been rejected, because the file format could not be recognized!", "", analyzer->filesRejected())), NOBR(tr("This usually means the file is damaged or the file format is not supported."))));
821 MUTILS_DELETE(analyzer);
822 m_banner->close();
826 * Add folder to source list
828 void MainWindow::addFolder(const QString &path, bool recursive, bool delayed)
830 QFileInfoList folderInfoList;
831 folderInfoList << QFileInfo(path);
832 QStringList fileList;
834 SHOW_BANNER(tr("Scanning folder(s) for files, please wait..."));
836 QApplication::processEvents();
837 MUtils::OS::check_key_state_esc();
839 while(!folderInfoList.isEmpty())
841 if(MUtils::OS::check_key_state_esc())
843 qWarning("Operation cancelled by user!");
844 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
845 fileList.clear();
846 break;
849 QDir currentDir(folderInfoList.takeFirst().canonicalFilePath());
850 QFileInfoList fileInfoList = currentDir.entryInfoList(QDir::Files | QDir::NoSymLinks);
852 while(!fileInfoList.isEmpty())
854 fileList << fileInfoList.takeFirst().canonicalFilePath();
857 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
859 if(recursive)
861 folderInfoList.append(currentDir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks));
862 QApplication::processEvents();
866 m_banner->close();
867 QApplication::processEvents();
869 if(!fileList.isEmpty())
871 if(delayed)
873 addFilesDelayed(fileList);
875 else
877 addFiles(fileList);
883 * Check for updates
885 bool MainWindow::checkForUpdates(void)
887 bool bReadyToInstall = false;
889 UpdateDialog *updateDialog = new UpdateDialog(m_settings, this);
890 updateDialog->exec();
892 if(updateDialog->getSuccess())
894 SHOW_CORNER_WIDGET(false);
895 m_settings->autoUpdateLastCheck(QDate::currentDate().toString(Qt::ISODate));
896 bReadyToInstall = updateDialog->updateReadyToInstall();
899 MUTILS_DELETE(updateDialog);
900 return bReadyToInstall;
904 * Refresh list of favorites
906 void MainWindow::refreshFavorites(void)
908 QList<QAction*> folderList = m_outputFolderFavoritesMenu->actions();
909 QStringList favorites = m_settings->favoriteOutputFolders().split("|", QString::SkipEmptyParts);
910 while(favorites.count() > 6) favorites.removeFirst();
912 while(!folderList.isEmpty())
914 QAction *currentItem = folderList.takeFirst();
915 if(currentItem->isSeparator()) break;
916 m_outputFolderFavoritesMenu->removeAction(currentItem);
917 MUTILS_DELETE(currentItem);
920 QAction *lastItem = m_outputFolderFavoritesMenu->actions().first();
922 while(!favorites.isEmpty())
924 QString path = favorites.takeLast();
925 if(QDir(path).exists())
927 QAction *action = new QAction(QIcon(":/icons/folder_go.png"), QDir::toNativeSeparators(path), this);
928 action->setData(path);
929 m_outputFolderFavoritesMenu->insertAction(lastItem, action);
930 connect(action, SIGNAL(triggered(bool)), this, SLOT(gotoFavoriteFolder()));
931 lastItem = action;
937 * Initilaize translation
939 void MainWindow::initializeTranslation(void)
941 bool translationLoaded = false;
943 //Try to load "external" translation file
944 if(!m_settings->currentLanguageFile().isEmpty())
946 const QString qmFilePath = QFileInfo(m_settings->currentLanguageFile()).canonicalFilePath();
947 if((!qmFilePath.isEmpty()) && QFileInfo(qmFilePath).exists() && QFileInfo(qmFilePath).isFile() && (QFileInfo(qmFilePath).suffix().compare("qm", Qt::CaseInsensitive) == 0))
949 if(MUtils::Translation::install_translator_from_file(qmFilePath))
951 QList<QAction*> actions = m_languageActionGroup->actions();
952 while(!actions.isEmpty()) actions.takeFirst()->setChecked(false);
953 ui->actionLoadTranslationFromFile->setChecked(true);
954 translationLoaded = true;
959 //Try to load "built-in" translation file
960 if(!translationLoaded)
962 QList<QAction*> languageActions = m_languageActionGroup->actions();
963 while(!languageActions.isEmpty())
965 QAction *currentLanguage = languageActions.takeFirst();
966 if(currentLanguage->data().toString().compare(m_settings->currentLanguage(), Qt::CaseInsensitive) == 0)
968 currentLanguage->setChecked(true);
969 languageActionActivated(currentLanguage);
970 translationLoaded = true;
975 //Fallback to default translation
976 if(!translationLoaded)
978 QList<QAction*> languageActions = m_languageActionGroup->actions();
979 while(!languageActions.isEmpty())
981 QAction *currentLanguage = languageActions.takeFirst();
982 if(currentLanguage->data().toString().compare(MUtils::Translation::DEFAULT_LANGID, Qt::CaseInsensitive) == 0)
984 currentLanguage->setChecked(true);
985 languageActionActivated(currentLanguage);
986 translationLoaded = true;
991 //Make sure we loaded some translation
992 if(!translationLoaded)
994 qFatal("Failed to load any translation, this is NOT supposed to happen!");
999 * Open a document link
1001 void MainWindow::openDocumentLink(QAction *const action)
1003 if(!(action->data().isValid() && (action->data().type() == QVariant::String)))
1005 qWarning("Cannot open document for this QAction!");
1006 return;
1009 //Try to open exitsing document file
1010 const QFileInfo document(action->data().toString());
1011 if(document.exists() && document.isFile() && (document.size() >= 1024))
1013 QDesktopServices::openUrl(QUrl::fromLocalFile(document.canonicalFilePath()));
1014 return;
1017 //Document not found -> fallback mode!
1018 qWarning("Document '%s' not found -> redirecting to the website!", MUTILS_UTF8(document.fileName()));
1019 const QUrl url(QString("%1/%2").arg(QString::fromLatin1(g_documents_base_url), document.fileName()));
1020 QDesktopServices::openUrl(url);
1023 ////////////////////////////////////////////////////////////
1024 // EVENTS
1025 ////////////////////////////////////////////////////////////
1028 * Window is about to be shown
1030 void MainWindow::showEvent(QShowEvent *event)
1032 m_accepted = false;
1033 resizeEvent(NULL);
1034 sourceModelChanged();
1036 if(!event->spontaneous())
1038 WITH_BLOCKED_SIGNALS(ui->tabWidget, setCurrentIndex, 0);
1039 tabPageChanged(ui->tabWidget->currentIndex(), true);
1042 if(m_firstTimeShown)
1044 m_firstTimeShown = false;
1045 QTimer::singleShot(0, this, SLOT(windowShown()));
1047 else
1049 if(m_settings->dropBoxWidgetEnabled())
1051 m_dropBox->setVisible(true);
1057 * Re-translate the UI
1059 void MainWindow::changeEvent(QEvent *e)
1061 QMainWindow::changeEvent(e);
1062 if(e->type() != QEvent::LanguageChange)
1064 return;
1067 int comboBoxIndex[8];
1069 //Backup combobox indices, as retranslateUi() resets
1070 comboBoxIndex[0] = ui->comboBoxMP3ChannelMode->currentIndex();
1071 comboBoxIndex[1] = ui->comboBoxSamplingRate->currentIndex();
1072 comboBoxIndex[2] = ui->comboBoxAACProfile->currentIndex();
1073 comboBoxIndex[3] = ui->comboBoxAftenCodingMode->currentIndex();
1074 comboBoxIndex[4] = ui->comboBoxAftenDRCMode->currentIndex();
1075 comboBoxIndex[5] = ui->comboBoxNormalizationMode->currentIndex();
1076 comboBoxIndex[6] = 0; //comboBoxOpusOptimize->currentIndex();
1077 comboBoxIndex[7] = ui->comboBoxOpusFramesize->currentIndex();
1079 //Re-translate from UIC
1080 ui->retranslateUi(this);
1082 //Restore combobox indices
1083 ui->comboBoxMP3ChannelMode->setCurrentIndex(comboBoxIndex[0]);
1084 ui->comboBoxSamplingRate->setCurrentIndex(comboBoxIndex[1]);
1085 ui->comboBoxAACProfile->setCurrentIndex(comboBoxIndex[2]);
1086 ui->comboBoxAftenCodingMode->setCurrentIndex(comboBoxIndex[3]);
1087 ui->comboBoxAftenDRCMode->setCurrentIndex(comboBoxIndex[4]);
1088 ui->comboBoxNormalizationMode->setCurrentIndex(comboBoxIndex[5]);
1089 //comboBoxOpusOptimize->setCurrentIndex(comboBoxIndex[6]);
1090 ui->comboBoxOpusFramesize->setCurrentIndex(comboBoxIndex[7]);
1092 //Update the window title
1093 if(MUTILS_DEBUG)
1095 setWindowTitle(QString("%1 [!!! DEBUG BUILD !!!]").arg(windowTitle()));
1097 else if(lamexp_version_demo())
1099 setWindowTitle(QString("%1 [%2]").arg(windowTitle(), tr("DEMO VERSION")));
1102 //Manually re-translate widgets that UIC doesn't handle
1103 m_outputFolderNoteBox->setText(tr("Initializing directory outline, please be patient..."));
1104 m_dropNoteLabel->setText(QString("<br><img src=\":/images/DropZone.png\"><br><br>%1").arg(tr("You can drop in audio files here!")));
1105 if(QLabel *cornerWidget = dynamic_cast<QLabel*>(ui->menubar->cornerWidget()))
1107 cornerWidget->setText(QString("<nobr><img src=\":/icons/exclamation_small.png\">&nbsp;<b style=\"color:darkred\">%1</b>&nbsp;&nbsp;&nbsp;</nobr>").arg(tr("Check for Updates")));
1109 m_showDetailsContextAction->setText(tr("Show Details"));
1110 m_previewContextAction->setText(tr("Open File in External Application"));
1111 m_findFileContextAction->setText(tr("Browse File Location"));
1112 m_showFolderContextAction->setText(tr("Browse Selected Folder"));
1113 m_refreshFolderContextAction->setText(tr("Refresh Directory Outline"));
1114 m_goUpFolderContextAction->setText(tr("Go To Parent Directory"));
1115 m_addFavoriteFolderAction->setText(tr("Bookmark Current Output Folder"));
1116 m_exportCsvContextAction->setText(tr("Export Meta Tags to CSV File"));
1117 m_importCsvContextAction->setText(tr("Import Meta Tags from CSV File"));
1119 //Force GUI update
1120 m_metaInfoModel->clearData();
1121 m_metaInfoModel->setData(m_metaInfoModel->index(4, 1), m_settings->metaInfoPosition());
1122 updateEncoder(m_settings->compressionEncoder());
1123 updateLameAlgoQuality(ui->sliderLameAlgoQuality->value());
1124 updateMaximumInstances(ui->sliderMaxInstances->value());
1125 renameOutputPatternChanged(ui->lineEditRenamePattern->text(), true);
1127 //Re-install shell integration
1128 if(m_settings->shellIntegrationEnabled())
1130 ShellIntegration::install();
1133 //Translate system menu
1134 MUtils::GUI::sysmenu_update(this, IDM_ABOUTBOX, ui->buttonAbout->text());
1136 //Force resize event
1137 QApplication::postEvent(this, new QResizeEvent(this->size(), QSize()));
1138 for(QObjectList::ConstIterator iter = this->children().constBegin(); iter != this->children().constEnd(); iter++)
1140 if(QWidget *child = dynamic_cast<QWidget*>(*iter))
1142 QApplication::postEvent(child, new QResizeEvent(child->size(), QSize()));
1146 //Force tabe page change
1147 tabPageChanged(ui->tabWidget->currentIndex(), true);
1151 * File dragged over window
1153 void MainWindow::dragEnterEvent(QDragEnterEvent *event)
1155 QStringList formats = event->mimeData()->formats();
1157 if(formats.contains("application/x-qt-windows-mime;value=\"FileNameW\"", Qt::CaseInsensitive) && formats.contains("text/uri-list", Qt::CaseInsensitive))
1159 event->acceptProposedAction();
1164 * File dropped onto window
1166 void MainWindow::dropEvent(QDropEvent *event)
1168 m_droppedFileList->clear();
1169 (*m_droppedFileList) << event->mimeData()->urls();
1170 if(!m_droppedFileList->isEmpty())
1172 PLAY_SOUND_OPTIONAL("drop", true);
1173 QTimer::singleShot(0, this, SLOT(handleDroppedFiles()));
1178 * Window tries to close
1180 void MainWindow::closeEvent(QCloseEvent *event)
1182 if(BANNER_VISIBLE || m_delayedFileTimer->isActive())
1184 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN);
1185 event->ignore();
1188 if(m_dropBox)
1190 m_dropBox->hide();
1195 * Window was resized
1197 void MainWindow::resizeEvent(QResizeEvent *event)
1199 if(event) QMainWindow::resizeEvent(event);
1201 if(QWidget *port = ui->sourceFileView->viewport())
1203 m_dropNoteLabel->setGeometry(port->geometry());
1206 if(QWidget *port = ui->outputFolderView->viewport())
1208 m_outputFolderNoteBox->setGeometry(16, (port->height() - 64) / 2, port->width() - 32, 64);
1213 * Key press event filter
1215 void MainWindow::keyPressEvent(QKeyEvent *e)
1217 if(e->key() == Qt::Key_Delete)
1219 if(ui->sourceFileView->isVisible())
1221 QTimer::singleShot(0, this, SLOT(removeFileButtonClicked()));
1222 return;
1226 if(e->modifiers().testFlag(Qt::ControlModifier) && (e->key() == Qt::Key_F5))
1228 initializeTranslation();
1229 MUtils::Sound::beep(MUtils::Sound::BEEP_NFO);
1230 return;
1233 if(e->key() == Qt::Key_F5)
1235 if(ui->outputFolderView->isVisible())
1237 QTimer::singleShot(0, this, SLOT(refreshFolderContextActionTriggered()));
1238 return;
1242 QMainWindow::keyPressEvent(e);
1246 * Event filter
1248 bool MainWindow::eventFilter(QObject *obj, QEvent *event)
1250 if(obj == m_fileSystemModel)
1252 if(QApplication::overrideCursor() == NULL)
1254 QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
1255 QTimer::singleShot(250, this, SLOT(restoreCursor()));
1259 return QMainWindow::eventFilter(obj, event);
1262 bool MainWindow::event(QEvent *e)
1264 switch(e->type())
1266 case MUtils::GUI::USER_EVENT_QUERYENDSESSION:
1267 qWarning("System is shutting down, main window prepares to close...");
1268 if(BANNER_VISIBLE) m_banner->close();
1269 if(m_delayedFileTimer->isActive()) m_delayedFileTimer->stop();
1270 return true;
1271 case MUtils::GUI::USER_EVENT_ENDSESSION:
1272 qWarning("System is shutting down, main window will close now...");
1273 if(isVisible())
1275 while(!close())
1277 QApplication::processEvents(QEventLoop::WaitForMoreEvents & QEventLoop::ExcludeUserInputEvents);
1280 m_fileListModel->clearFiles();
1281 return true;
1282 case QEvent::MouseButtonPress:
1283 if(ui->outputFolderEdit->isVisible())
1285 QTimer::singleShot(0, this, SLOT(outputFolderEditFinished()));
1287 default:
1288 return QMainWindow::event(e);
1292 bool MainWindow::winEvent(MSG *message, long *result)
1294 if(MUtils::GUI::sysmenu_check_msg(message, IDM_ABOUTBOX))
1296 QTimer::singleShot(0, ui->buttonAbout, SLOT(click()));
1297 *result = 0;
1298 return true;
1300 return false;
1303 ////////////////////////////////////////////////////////////
1304 // Slots
1305 ////////////////////////////////////////////////////////////
1307 // =========================================================
1308 // Show window slots
1309 // =========================================================
1312 * Window shown
1314 void MainWindow::windowShown(void)
1316 const MUtils::OS::ArgumentMap &arguments = MUtils::OS::arguments(); //QApplication::arguments();
1318 //Force resize event
1319 resizeEvent(NULL);
1321 //First run?
1322 const bool firstRun = arguments.contains("first-run");
1324 //Check license
1325 if((m_settings->licenseAccepted() <= 0) || firstRun)
1327 int iAccepted = m_settings->licenseAccepted();
1329 if((iAccepted == 0) || firstRun)
1331 AboutDialog *about = new AboutDialog(m_settings, this, true);
1332 iAccepted = about->exec();
1333 if(iAccepted <= 0) iAccepted = -2;
1334 MUTILS_DELETE(about);
1337 if(iAccepted <= 0)
1339 m_settings->licenseAccepted(++iAccepted);
1340 m_settings->syncNow();
1341 QApplication::processEvents();
1342 MUtils::Sound::play_sound("whammy", false);
1343 QMessageBox::critical(this, tr("License Declined"), tr("You have declined the license. Consequently the application will exit now!"), tr("Goodbye!"));
1344 QFileInfo uninstallerInfo = QFileInfo(QString("%1/Uninstall.exe").arg(QApplication::applicationDirPath()));
1345 if(uninstallerInfo.exists())
1347 QString uninstallerDir = uninstallerInfo.canonicalPath();
1348 QString uninstallerPath = uninstallerInfo.canonicalFilePath();
1349 for(int i = 0; i < 3; i++)
1351 if(MUtils::OS::shell_open(this, QDir::toNativeSeparators(uninstallerPath), "/Force", QDir::toNativeSeparators(uninstallerDir))) break;
1354 QApplication::quit();
1355 return;
1358 MUtils::Sound::play_sound("woohoo", false);
1359 m_settings->licenseAccepted(1);
1360 m_settings->syncNow();
1361 if(lamexp_version_demo()) showAnnounceBox();
1364 //Check for expiration
1365 if(lamexp_version_demo())
1367 if(MUtils::OS::current_date() >= lamexp_version_expires())
1369 qWarning("Binary has expired !!!");
1370 MUtils::Sound::play_sound("whammy", false);
1371 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)
1373 checkForUpdates();
1375 QApplication::quit();
1376 return;
1380 //Slow startup indicator
1381 if(m_settings->slowStartup() && m_settings->antivirNotificationsEnabled())
1383 QString message;
1384 message += NOBR(tr("It seems that a bogus anti-virus software is slowing down the startup of LameXP.")).append("<br>");
1385 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>");
1386 if(QMessageBox::warning(this, tr("Slow Startup"), message, tr("Discard"), tr("Don't Show Again")) == 1)
1388 m_settings->antivirNotificationsEnabled(false);
1389 ui->actionDisableSlowStartupNotifications->setChecked(!m_settings->antivirNotificationsEnabled());
1393 //Update reminder
1394 if(MUtils::OS::current_date() >= MUtils::Version::app_build_date().addYears(1))
1396 qWarning("Binary is more than a year old, time to update!");
1397 SHOW_CORNER_WIDGET(true);
1398 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"));
1399 switch(ret)
1401 case 0:
1402 if(checkForUpdates())
1404 QApplication::quit();
1405 return;
1407 break;
1408 case 1:
1409 QApplication::quit();
1410 return;
1411 default:
1412 QEventLoop loop; QTimer::singleShot(7000, &loop, SLOT(quit()));
1413 MUtils::Sound::play_sound("waiting", true);
1414 SHOW_BANNER_ARG(tr("Skipping update check this time, please be patient..."), &loop);
1415 break;
1418 else
1420 QDate lastUpdateCheck = QDate::fromString(m_settings->autoUpdateLastCheck(), Qt::ISODate);
1421 if((!firstRun) && ((!lastUpdateCheck.isValid()) || (MUtils::OS::current_date() >= lastUpdateCheck.addDays(14))))
1423 SHOW_CORNER_WIDGET(true);
1424 if(m_settings->autoUpdateEnabled())
1426 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)
1428 if(checkForUpdates())
1430 QApplication::quit();
1431 return;
1438 //Check for AAC support
1439 const int aacEncoder = EncoderRegistry::getAacEncoder();
1440 if(aacEncoder == SettingsModel::AAC_ENCODER_NERO)
1442 if(m_settings->neroAacNotificationsEnabled())
1444 if(lamexp_tools_version("neroAacEnc.exe") < lamexp_toolver_neroaac())
1446 QString messageText;
1447 messageText += NOBR(tr("LameXP detected that your version of the Nero AAC encoder is outdated!")).append("<br>");
1448 messageText += NOBR(tr("The current version available is %1 (or later), but you still have version %2 installed.").arg(lamexp_version2string("?.?.?.?", lamexp_toolver_neroaac(), tr("n/a")), lamexp_version2string("?.?.?.?", lamexp_tools_version("neroAacEnc.exe"), tr("n/a")))).append("<br><br>");
1449 messageText += NOBR(tr("You can download the latest version of the Nero AAC encoder from the Nero website at:")).append("<br>");
1450 messageText += "<nobr><tt>" + LINK(AboutDialog::neroAacUrl) + "</tt></nobr><br><br>";
1451 messageText += NOBR(tr("(Hint: Please ignore the name of the downloaded ZIP file and check the included 'changelog.txt' instead!)")).append("<br>");
1452 QMessageBox::information(this, tr("AAC Encoder Outdated"), messageText);
1456 else
1458 if(m_settings->neroAacNotificationsEnabled() && (aacEncoder <= SettingsModel::AAC_ENCODER_NONE))
1460 QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
1461 if(appPath.isEmpty()) appPath = QCoreApplication::applicationDirPath();
1462 QString messageText;
1463 messageText += NOBR(tr("The Nero AAC encoder could not be found. AAC encoding support will be disabled.")).append("<br>");
1464 messageText += NOBR(tr("Please put 'neroAacEnc.exe', 'neroAacDec.exe' and 'neroAacTag.exe' into the LameXP directory!")).append("<br><br>");
1465 messageText += NOBR(tr("Your LameXP directory is located here:")).append("<br>");
1466 messageText += QString("<nobr><tt>%1</tt></nobr><br><br>").arg(FSLINK(QDir::toNativeSeparators(appPath)));
1467 messageText += NOBR(tr("You can download the Nero AAC encoder for free from the official Nero website at:")).append("<br>");
1468 messageText += "<nobr><tt>" + LINK(AboutDialog::neroAacUrl) + "</tt></nobr><br>";
1469 if(QMessageBox::information(this, tr("AAC Support Disabled"), messageText, tr("Discard"), tr("Don't Show Again")) == 1)
1471 m_settings->neroAacNotificationsEnabled(false);
1472 ui->actionDisableNeroAacNotifications->setChecked(!m_settings->neroAacNotificationsEnabled());
1477 //Add files from the command-line
1478 QStringList addedFiles;
1479 foreach(const QString &value, arguments.values("add"))
1481 if(!value.isEmpty())
1483 QFileInfo currentFile(value);
1484 qDebug("Adding file from CLI: %s", MUTILS_UTF8(currentFile.absoluteFilePath()));
1485 addedFiles.append(currentFile.absoluteFilePath());
1488 if(!addedFiles.isEmpty())
1490 addFilesDelayed(addedFiles);
1493 //Add folders from the command-line
1494 foreach(const QString &value, arguments.values("add-folder"))
1496 if(!value.isEmpty())
1498 const QFileInfo currentFile(value);
1499 qDebug("Adding folder from CLI: %s", MUTILS_UTF8(currentFile.absoluteFilePath()));
1500 addFolder(currentFile.absoluteFilePath(), false, true);
1503 foreach(const QString &value, arguments.values("add-recursive"))
1505 if(!value.isEmpty())
1507 const QFileInfo currentFile(value);
1508 qDebug("Adding folder recursively from CLI: %s", MUTILS_UTF8(currentFile.absoluteFilePath()));
1509 addFolder(currentFile.absoluteFilePath(), true, true);
1513 //Enable shell integration
1514 if(m_settings->shellIntegrationEnabled())
1516 ShellIntegration::install();
1519 //Make DropBox visible
1520 if(m_settings->dropBoxWidgetEnabled())
1522 m_dropBox->setVisible(true);
1527 * Show announce box
1529 void MainWindow::showAnnounceBox(void)
1531 const unsigned int timeout = 8U;
1533 const QString announceText = QString("%1<br><br>%2<br><nobr><tt>%3</tt></nobr><br>").arg
1535 NOBR("We are still looking for LameXP translators!"),
1536 NOBR("If you are willing to translate LameXP to your language or to complete an existing translation, please refer to:"),
1537 LINK("http://lamexp.sourceforge.net/doc/Translate.html")
1540 QMessageBox *announceBox = new QMessageBox(QMessageBox::Warning, "We want you!", announceText, QMessageBox::NoButton, this);
1541 announceBox->setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
1542 announceBox->setIconPixmap(QIcon(":/images/Announcement.png").pixmap(64,79));
1544 QTimer *timers[timeout+1];
1545 QPushButton *buttons[timeout+1];
1547 for(unsigned int i = 0; i <= timeout; i++)
1549 QString text = (i > 0) ? QString("%1 (%2)").arg(tr("Discard"), QString::number(i)) : tr("Discard");
1550 buttons[i] = announceBox->addButton(text, (i > 0) ? QMessageBox::NoRole : QMessageBox::AcceptRole);
1553 for(unsigned int i = 0; i <= timeout; i++)
1555 buttons[i]->setEnabled(i == 0);
1556 buttons[i]->setVisible(i == timeout);
1559 for(unsigned int i = 0; i < timeout; i++)
1561 timers[i] = new QTimer(this);
1562 timers[i]->setSingleShot(true);
1563 timers[i]->setInterval(1000);
1564 connect(timers[i], SIGNAL(timeout()), buttons[i+1], SLOT(hide()));
1565 connect(timers[i], SIGNAL(timeout()), buttons[i], SLOT(show()));
1566 if(i > 0)
1568 connect(timers[i], SIGNAL(timeout()), timers[i-1], SLOT(start()));
1572 timers[timeout-1]->start();
1573 announceBox->exec();
1575 for(unsigned int i = 0; i < timeout; i++)
1577 timers[i]->stop();
1578 MUTILS_DELETE(timers[i]);
1581 MUTILS_DELETE(announceBox);
1584 // =========================================================
1585 // Main button solots
1586 // =========================================================
1589 * Encode button
1591 void MainWindow::encodeButtonClicked(void)
1593 static const unsigned __int64 oneGigabyte = 1073741824ui64;
1594 static const unsigned __int64 minimumFreeDiskspaceMultiplier = 2ui64;
1595 static const char *writeTestBuffer = "LAMEXP_WRITE_TEST";
1597 ABORT_IF_BUSY;
1599 if(m_fileListModel->rowCount() < 1)
1601 QMessageBox::warning(this, tr("LameXP"), NOBR(tr("You must add at least one file to the list before proceeding!")));
1602 ui->tabWidget->setCurrentIndex(0);
1603 return;
1606 QString tempFolder = m_settings->customTempPathEnabled() ? m_settings->customTempPath() : MUtils::temp_folder();
1607 if(!QFileInfo(tempFolder).exists() || !QFileInfo(tempFolder).isDir())
1609 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)
1611 SET_CHECKBOX_STATE(ui->checkBoxUseSystemTempFolder, m_settings->customTempPathEnabledDefault());
1613 return;
1616 quint64 currentFreeDiskspace = 0;
1617 if(MUtils::OS::free_diskspace(tempFolder, currentFreeDiskspace))
1619 if(currentFreeDiskspace < (oneGigabyte * minimumFreeDiskspaceMultiplier))
1621 QStringList tempFolderParts = tempFolder.split("/", QString::SkipEmptyParts, Qt::CaseInsensitive);
1622 tempFolderParts.takeLast();
1623 PLAY_SOUND_OPTIONAL("whammy", false);
1624 QString lowDiskspaceMsg = QString("%1<br>%2<br><br>%3<br>%4<br>").arg
1626 NOBR(tr("There are less than %1 GB of free diskspace available on your system's TEMP folder.").arg(QString::number(minimumFreeDiskspaceMultiplier))),
1627 NOBR(tr("It is highly recommend to free up more diskspace before proceeding with the encode!")),
1628 NOBR(tr("Your TEMP folder is located at:")),
1629 QString("<nobr><tt>%1</tt></nobr>").arg(FSLINK(tempFolderParts.join("\\")))
1631 switch(QMessageBox::warning(this, tr("Low Diskspace Warning"), lowDiskspaceMsg, tr("Abort Encoding Process"), tr("Clean Disk Now"), tr("Ignore")))
1633 case 1:
1634 QProcess::startDetached(QString("%1/cleanmgr.exe").arg(MUtils::OS::known_folder(MUtils::OS::FOLDER_SYSTEMFOLDER)), QStringList() << "/D" << tempFolderParts.first());
1635 case 0:
1636 return;
1637 break;
1638 default:
1639 QMessageBox::warning(this, tr("Low Diskspace"), NOBR(tr("You are proceeding with low diskspace. Problems might occur!")));
1640 break;
1645 switch(m_settings->compressionEncoder())
1647 case SettingsModel::MP3Encoder:
1648 case SettingsModel::VorbisEncoder:
1649 case SettingsModel::AACEncoder:
1650 case SettingsModel::AC3Encoder:
1651 case SettingsModel::FLACEncoder:
1652 case SettingsModel::OpusEncoder:
1653 case SettingsModel::DCAEncoder:
1654 case SettingsModel::MACEncoder:
1655 case SettingsModel::PCMEncoder:
1656 break;
1657 default:
1658 QMessageBox::warning(this, tr("LameXP"), tr("Sorry, an unsupported encoder has been chosen!"));
1659 ui->tabWidget->setCurrentIndex(3);
1660 return;
1663 if(!m_settings->outputToSourceDir())
1665 QFile writeTest(QString("%1/~%2.txt").arg(m_settings->outputDir(), MUtils::rand_str()));
1666 if(!(writeTest.open(QIODevice::ReadWrite) && (writeTest.write(writeTestBuffer) == strlen(writeTestBuffer))))
1668 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!")));
1669 ui->tabWidget->setCurrentIndex(1);
1670 return;
1672 else
1674 writeTest.close();
1675 writeTest.remove();
1679 m_accepted = true;
1680 close();
1684 * About button
1686 void MainWindow::aboutButtonClicked(void)
1688 ABORT_IF_BUSY;
1690 TEMP_HIDE_DROPBOX
1692 AboutDialog *aboutBox = new AboutDialog(m_settings, this);
1693 aboutBox->exec();
1694 MUTILS_DELETE(aboutBox);
1699 * Close button
1701 void MainWindow::closeButtonClicked(void)
1703 ABORT_IF_BUSY;
1704 close();
1707 // =========================================================
1708 // Tab widget slots
1709 // =========================================================
1712 * Tab page changed
1714 void MainWindow::tabPageChanged(int idx, const bool silent)
1716 resizeEvent(NULL);
1718 //Update "view" menu
1719 QList<QAction*> actions = m_tabActionGroup->actions();
1720 for(int i = 0; i < actions.count(); i++)
1722 bool ok = false;
1723 int actionIndex = actions.at(i)->data().toInt(&ok);
1724 if(ok && actionIndex == idx)
1726 actions.at(i)->setChecked(true);
1730 //Play tick sound
1731 if(!silent)
1733 PLAY_SOUND_OPTIONAL("tick", true);
1736 int initialWidth = this->width();
1737 int maximumWidth = QApplication::desktop()->availableGeometry().width();
1739 //Make sure all tab headers are fully visible
1740 if(this->isVisible())
1742 int delta = ui->tabWidget->sizeHint().width() - ui->tabWidget->width();
1743 if(delta > 0)
1745 this->resize(qMin(this->width() + delta, maximumWidth), this->height());
1749 //Tab specific operations
1750 if(idx == ui->tabWidget->indexOf(ui->tabOptions) && ui->scrollArea->widget() && this->isVisible())
1752 ui->scrollArea->widget()->updateGeometry();
1753 ui->scrollArea->viewport()->updateGeometry();
1754 qApp->processEvents();
1755 int delta = ui->scrollArea->widget()->width() - ui->scrollArea->viewport()->width();
1756 if(delta > 0)
1758 this->resize(qMin(this->width() + delta, maximumWidth), this->height());
1761 else if(idx == ui->tabWidget->indexOf(ui->tabSourceFiles))
1763 m_dropNoteLabel->setGeometry(0, 0, ui->sourceFileView->width(), ui->sourceFileView->height());
1765 else if(idx == ui->tabWidget->indexOf(ui->tabOutputDir))
1767 if(!m_fileSystemModel)
1769 QTimer::singleShot(125, this, SLOT(initOutputFolderModel()));
1771 else
1773 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
1777 //Center window around previous position
1778 if(initialWidth < this->width())
1780 QPoint prevPos = this->pos();
1781 int delta = (this->width() - initialWidth) >> 2;
1782 move(prevPos.x() - delta, prevPos.y());
1787 * Tab action triggered
1789 void MainWindow::tabActionActivated(QAction *action)
1791 if(action && action->data().isValid())
1793 bool ok = false;
1794 int index = action->data().toInt(&ok);
1795 if(ok)
1797 ui->tabWidget->setCurrentIndex(index);
1802 // =========================================================
1803 // Menubar slots
1804 // =========================================================
1807 * Handle corner widget Event
1809 void MainWindow::cornerWidgetEventOccurred(QWidget *sender, QEvent *event)
1811 if(event->type() == QEvent::MouseButtonPress)
1813 QTimer::singleShot(0, this, SLOT(checkUpdatesActionActivated()));
1817 // =========================================================
1818 // View menu slots
1819 // =========================================================
1822 * Style action triggered
1824 void MainWindow::styleActionActivated(QAction *action)
1826 //Change style setting
1827 if(action && action->data().isValid())
1829 bool ok = false;
1830 int actionIndex = action->data().toInt(&ok);
1831 if(ok)
1833 m_settings->interfaceStyle(actionIndex);
1837 //Set up the new style
1838 switch(m_settings->interfaceStyle())
1840 case 1:
1841 if(ui->actionStyleCleanlooks->isEnabled())
1843 ui->actionStyleCleanlooks->setChecked(true);
1844 QApplication::setStyle(new QCleanlooksStyle());
1845 break;
1847 case 2:
1848 if(ui->actionStyleWindowsVista->isEnabled())
1850 ui->actionStyleWindowsVista->setChecked(true);
1851 QApplication::setStyle(new QWindowsVistaStyle());
1852 break;
1854 case 3:
1855 if(ui->actionStyleWindowsXP->isEnabled())
1857 ui->actionStyleWindowsXP->setChecked(true);
1858 QApplication::setStyle(new QWindowsXPStyle());
1859 break;
1861 case 4:
1862 if(ui->actionStyleWindowsClassic->isEnabled())
1864 ui->actionStyleWindowsClassic->setChecked(true);
1865 QApplication::setStyle(new QWindowsStyle());
1866 break;
1868 default:
1869 ui->actionStylePlastique->setChecked(true);
1870 QApplication::setStyle(new QPlastiqueStyle());
1871 break;
1874 //Force re-translate after style change
1875 if(QEvent *e = new QEvent(QEvent::LanguageChange))
1877 changeEvent(e);
1878 MUTILS_DELETE(e);
1881 //Make transparent
1882 const type_info &styleType = typeid(*qApp->style());
1883 const bool bTransparent = ((typeid(QWindowsVistaStyle) == styleType) || (typeid(QWindowsXPStyle) == styleType));
1884 MAKE_TRANSPARENT(ui->scrollArea, bTransparent);
1886 //Also force a re-size event
1887 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
1888 resizeEvent(NULL);
1892 * Language action triggered
1894 void MainWindow::languageActionActivated(QAction *action)
1896 if(action->data().type() == QVariant::String)
1898 QString langId = action->data().toString();
1900 if(MUtils::Translation::install_translator(langId))
1902 action->setChecked(true);
1903 ui->actionLoadTranslationFromFile->setChecked(false);
1904 m_settings->currentLanguage(langId);
1905 m_settings->currentLanguageFile(QString());
1911 * Load language from file action triggered
1913 void MainWindow::languageFromFileActionActivated(bool checked)
1915 QFileDialog dialog(this, tr("Load Translation"));
1916 dialog.setFileMode(QFileDialog::ExistingFile);
1917 dialog.setNameFilter(QString("%1 (*.qm)").arg(tr("Translation Files")));
1919 if(dialog.exec())
1921 QStringList selectedFiles = dialog.selectedFiles();
1922 const QString qmFile = QFileInfo(selectedFiles.first()).canonicalFilePath();
1923 if(MUtils::Translation::install_translator_from_file(qmFile))
1925 QList<QAction*> actions = m_languageActionGroup->actions();
1926 while(!actions.isEmpty())
1928 actions.takeFirst()->setChecked(false);
1930 ui->actionLoadTranslationFromFile->setChecked(true);
1931 m_settings->currentLanguageFile(qmFile);
1933 else
1935 languageActionActivated(m_languageActionGroup->actions().first());
1940 // =========================================================
1941 // Tools menu slots
1942 // =========================================================
1945 * Disable update reminder action
1947 void MainWindow::disableUpdateReminderActionTriggered(bool checked)
1949 if(checked)
1951 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))
1953 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!"))));
1954 m_settings->autoUpdateEnabled(false);
1956 else
1958 m_settings->autoUpdateEnabled(true);
1961 else
1963 QMessageBox::information(this, tr("Update Reminder"), NOBR(tr("The update reminder has been re-enabled.")));
1964 m_settings->autoUpdateEnabled(true);
1967 ui->actionDisableUpdateReminder->setChecked(!m_settings->autoUpdateEnabled());
1971 * Disable sound effects action
1973 void MainWindow::disableSoundsActionTriggered(bool checked)
1975 if(checked)
1977 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))
1979 QMessageBox::information(this, tr("Sound Effects"), NOBR(tr("All sound effects have been disabled.")));
1980 m_settings->soundsEnabled(false);
1982 else
1984 m_settings->soundsEnabled(true);
1987 else
1989 QMessageBox::information(this, tr("Sound Effects"), NOBR(tr("The sound effects have been re-enabled.")));
1990 m_settings->soundsEnabled(true);
1993 ui->actionDisableSounds->setChecked(!m_settings->soundsEnabled());
1997 * Disable Nero AAC encoder action
1999 void MainWindow::disableNeroAacNotificationsActionTriggered(bool checked)
2001 if(checked)
2003 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))
2005 QMessageBox::information(this, tr("Nero AAC Notifications"), NOBR(tr("All Nero AAC Encoder notifications have been disabled.")));
2006 m_settings->neroAacNotificationsEnabled(false);
2008 else
2010 m_settings->neroAacNotificationsEnabled(true);
2013 else
2015 QMessageBox::information(this, tr("Nero AAC Notifications"), NOBR(tr("The Nero AAC Encoder notifications have been re-enabled.")));
2016 m_settings->neroAacNotificationsEnabled(true);
2019 ui->actionDisableNeroAacNotifications->setChecked(!m_settings->neroAacNotificationsEnabled());
2023 * Disable slow startup action
2025 void MainWindow::disableSlowStartupNotificationsActionTriggered(bool checked)
2027 if(checked)
2029 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))
2031 QMessageBox::information(this, tr("Slow Startup Notifications"), NOBR(tr("The slow startup notifications have been disabled.")));
2032 m_settings->antivirNotificationsEnabled(false);
2034 else
2036 m_settings->antivirNotificationsEnabled(true);
2039 else
2041 QMessageBox::information(this, tr("Slow Startup Notifications"), NOBR(tr("The slow startup notifications have been re-enabled.")));
2042 m_settings->antivirNotificationsEnabled(true);
2045 ui->actionDisableSlowStartupNotifications->setChecked(!m_settings->antivirNotificationsEnabled());
2049 * Import a Cue Sheet file
2051 void MainWindow::importCueSheetActionTriggered(bool checked)
2053 ABORT_IF_BUSY;
2055 TEMP_HIDE_DROPBOX
2057 while(true)
2059 int result = 0;
2060 QString selectedCueFile;
2062 if(MUtils::GUI::themes_enabled())
2064 selectedCueFile = QFileDialog::getOpenFileName(this, tr("Open Cue Sheet"), m_settings->mostRecentInputPath(), QString("%1 (*.cue)").arg(tr("Cue Sheet File")));
2066 else
2068 QFileDialog dialog(this, tr("Open Cue Sheet"));
2069 dialog.setFileMode(QFileDialog::ExistingFile);
2070 dialog.setNameFilter(QString("%1 (*.cue)").arg(tr("Cue Sheet File")));
2071 dialog.setDirectory(m_settings->mostRecentInputPath());
2072 if(dialog.exec())
2074 selectedCueFile = dialog.selectedFiles().first();
2078 if(!selectedCueFile.isEmpty())
2080 m_settings->mostRecentInputPath(QFileInfo(selectedCueFile).canonicalPath());
2081 CueImportDialog *cueImporter = new CueImportDialog(this, m_fileListModel, selectedCueFile, m_settings);
2082 result = cueImporter->exec();
2083 MUTILS_DELETE(cueImporter);
2086 if(result == QDialog::Accepted)
2088 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
2089 ui->sourceFileView->update();
2090 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
2091 ui->sourceFileView->scrollToBottom();
2092 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
2095 if(result != (-1)) break;
2101 * Show the "drop box" widget
2103 void MainWindow::showDropBoxWidgetActionTriggered(bool checked)
2105 m_settings->dropBoxWidgetEnabled(true);
2107 if(!m_dropBox->isVisible())
2109 m_dropBox->show();
2110 QTimer::singleShot(2500, m_dropBox, SLOT(showToolTip()));
2113 MUtils::GUI::blink_window(m_dropBox);
2117 * Check for beta (pre-release) updates
2119 void MainWindow::checkForBetaUpdatesActionTriggered(bool checked)
2121 bool checkUpdatesNow = false;
2123 if(checked)
2125 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))
2127 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")))
2129 checkUpdatesNow = true;
2131 m_settings->autoUpdateCheckBeta(true);
2133 else
2135 m_settings->autoUpdateCheckBeta(false);
2138 else
2140 QMessageBox::information(this, tr("Beta Updates"), NOBR(tr("LameXP will <i>not</i> check for Beta (pre-release) updates from now on.")));
2141 m_settings->autoUpdateCheckBeta(false);
2144 ui->actionCheckForBetaUpdates->setChecked(m_settings->autoUpdateCheckBeta());
2146 if(checkUpdatesNow)
2148 if(checkForUpdates())
2150 QApplication::quit();
2156 * Hibernate computer action
2158 void MainWindow::hibernateComputerActionTriggered(bool checked)
2160 if(checked)
2162 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))
2164 QMessageBox::information(this, tr("Hibernate Computer"), NOBR(tr("LameXP will hibernate the computer on shutdown from now on.")));
2165 m_settings->hibernateComputer(true);
2167 else
2169 m_settings->hibernateComputer(false);
2172 else
2174 QMessageBox::information(this, tr("Hibernate Computer"), NOBR(tr("LameXP will <i>not</i> hibernate the computer on shutdown from now on.")));
2175 m_settings->hibernateComputer(false);
2178 ui->actionHibernateComputer->setChecked(m_settings->hibernateComputer());
2182 * Disable shell integration action
2184 void MainWindow::disableShellIntegrationActionTriggered(bool checked)
2186 if(checked)
2188 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))
2190 ShellIntegration::remove();
2191 QMessageBox::information(this, tr("Shell Integration"), NOBR(tr("The LameXP shell integration has been disabled.")));
2192 m_settings->shellIntegrationEnabled(false);
2194 else
2196 m_settings->shellIntegrationEnabled(true);
2199 else
2201 ShellIntegration::install();
2202 QMessageBox::information(this, tr("Shell Integration"), NOBR(tr("The LameXP shell integration has been re-enabled.")));
2203 m_settings->shellIntegrationEnabled(true);
2206 ui->actionDisableShellIntegration->setChecked(!m_settings->shellIntegrationEnabled());
2208 if(lamexp_version_portable() && ui->actionDisableShellIntegration->isChecked())
2210 ui->actionDisableShellIntegration->setEnabled(false);
2214 // =========================================================
2215 // Help menu slots
2216 // =========================================================
2219 * Visit homepage action
2221 void MainWindow::visitHomepageActionActivated(void)
2223 if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
2225 if(action->data().isValid() && (action->data().type() == QVariant::String))
2227 QDesktopServices::openUrl(QUrl(action->data().toString()));
2233 * Show document
2235 void MainWindow::documentActionActivated(void)
2237 if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
2239 openDocumentLink(action);
2244 * Check for updates action
2246 void MainWindow::checkUpdatesActionActivated(void)
2248 ABORT_IF_BUSY;
2249 bool bFlag = false;
2251 TEMP_HIDE_DROPBOX
2253 bFlag = checkForUpdates();
2256 if(bFlag)
2258 QApplication::quit();
2262 // =========================================================
2263 // Source file slots
2264 // =========================================================
2267 * Add file(s) button
2269 void MainWindow::addFilesButtonClicked(void)
2271 ABORT_IF_BUSY;
2273 TEMP_HIDE_DROPBOX
2275 if(MUtils::GUI::themes_enabled())
2277 QStringList fileTypeFilters = DecoderRegistry::getSupportedTypes();
2278 QStringList selectedFiles = QFileDialog::getOpenFileNames(this, tr("Add file(s)"), m_settings->mostRecentInputPath(), fileTypeFilters.join(";;"));
2279 if(!selectedFiles.isEmpty())
2281 m_settings->mostRecentInputPath(QFileInfo(selectedFiles.first()).canonicalPath());
2282 addFiles(selectedFiles);
2285 else
2287 QFileDialog dialog(this, tr("Add file(s)"));
2288 QStringList fileTypeFilters = DecoderRegistry::getSupportedTypes();
2289 dialog.setFileMode(QFileDialog::ExistingFiles);
2290 dialog.setNameFilter(fileTypeFilters.join(";;"));
2291 dialog.setDirectory(m_settings->mostRecentInputPath());
2292 if(dialog.exec())
2294 QStringList selectedFiles = dialog.selectedFiles();
2295 if(!selectedFiles.isEmpty())
2297 m_settings->mostRecentInputPath(QFileInfo(selectedFiles.first()).canonicalPath());
2298 addFiles(selectedFiles);
2306 * Open folder action
2308 void MainWindow::openFolderActionActivated(void)
2310 ABORT_IF_BUSY;
2311 QString selectedFolder;
2313 if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
2315 TEMP_HIDE_DROPBOX
2317 if(MUtils::GUI::themes_enabled())
2319 selectedFolder = QFileDialog::getExistingDirectory(this, tr("Add Folder"), m_settings->mostRecentInputPath());
2321 else
2323 QFileDialog dialog(this, tr("Add Folder"));
2324 dialog.setFileMode(QFileDialog::DirectoryOnly);
2325 dialog.setDirectory(m_settings->mostRecentInputPath());
2326 if(dialog.exec())
2328 selectedFolder = dialog.selectedFiles().first();
2332 if(!selectedFolder.isEmpty())
2334 m_settings->mostRecentInputPath(QDir(selectedFolder).canonicalPath());
2335 addFolder(selectedFolder, action->data().toBool());
2342 * Remove file button
2344 void MainWindow::removeFileButtonClicked(void)
2346 if(ui->sourceFileView->currentIndex().isValid())
2348 int iRow = ui->sourceFileView->currentIndex().row();
2349 m_fileListModel->removeFile(ui->sourceFileView->currentIndex());
2350 ui->sourceFileView->selectRow(iRow < m_fileListModel->rowCount() ? iRow : m_fileListModel->rowCount()-1);
2355 * Clear files button
2357 void MainWindow::clearFilesButtonClicked(void)
2359 m_fileListModel->clearFiles();
2363 * Move file up button
2365 void MainWindow::fileUpButtonClicked(void)
2367 if(ui->sourceFileView->currentIndex().isValid())
2369 int iRow = ui->sourceFileView->currentIndex().row() - 1;
2370 m_fileListModel->moveFile(ui->sourceFileView->currentIndex(), -1);
2371 ui->sourceFileView->selectRow(iRow >= 0 ? iRow : 0);
2376 * Move file down button
2378 void MainWindow::fileDownButtonClicked(void)
2380 if(ui->sourceFileView->currentIndex().isValid())
2382 int iRow = ui->sourceFileView->currentIndex().row() + 1;
2383 m_fileListModel->moveFile(ui->sourceFileView->currentIndex(), 1);
2384 ui->sourceFileView->selectRow(iRow < m_fileListModel->rowCount() ? iRow : m_fileListModel->rowCount()-1);
2389 * Show details button
2391 void MainWindow::showDetailsButtonClicked(void)
2393 ABORT_IF_BUSY;
2395 int iResult = 0;
2396 MetaInfoDialog *metaInfoDialog = new MetaInfoDialog(this);
2397 QModelIndex index = ui->sourceFileView->currentIndex();
2399 while(index.isValid())
2401 if(iResult > 0)
2403 index = m_fileListModel->index(index.row() + 1, index.column());
2404 ui->sourceFileView->selectRow(index.row());
2406 if(iResult < 0)
2408 index = m_fileListModel->index(index.row() - 1, index.column());
2409 ui->sourceFileView->selectRow(index.row());
2412 AudioFileModel &file = (*m_fileListModel)[index];
2413 TEMP_HIDE_DROPBOX
2415 iResult = metaInfoDialog->exec(file, index.row() > 0, index.row() < m_fileListModel->rowCount() - 1);
2418 //Copy all info to Meta Info tab
2419 if(iResult == INT_MAX)
2421 m_metaInfoModel->assignInfoFrom(file);
2422 ui->tabWidget->setCurrentIndex(ui->tabWidget->indexOf(ui->tabMetaData));
2423 break;
2426 if(!iResult) break;
2429 MUTILS_DELETE(metaInfoDialog);
2430 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
2431 sourceFilesScrollbarMoved(0);
2435 * Show context menu for source files
2437 void MainWindow::sourceFilesContextMenu(const QPoint &pos)
2439 QAbstractScrollArea *scrollArea = dynamic_cast<QAbstractScrollArea*>(QObject::sender());
2440 QWidget *sender = scrollArea ? scrollArea->viewport() : dynamic_cast<QWidget*>(QObject::sender());
2442 if(sender)
2444 if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0)
2446 m_sourceFilesContextMenu->popup(sender->mapToGlobal(pos));
2452 * Scrollbar of source files moved
2454 void MainWindow::sourceFilesScrollbarMoved(int)
2456 ui->sourceFileView->resizeColumnToContents(0);
2460 * Open selected file in external player
2462 void MainWindow::previewContextActionTriggered(void)
2464 QModelIndex index = ui->sourceFileView->currentIndex();
2465 if(!index.isValid())
2467 return;
2470 if(!MUtils::OS::open_media_file(m_fileListModel->getFile(index).filePath()))
2472 qDebug("Player not found, falling back to default application...");
2473 QDesktopServices::openUrl(QString("file:///").append(m_fileListModel->getFile(index).filePath()));
2478 * Find selected file in explorer
2480 void MainWindow::findFileContextActionTriggered(void)
2482 QModelIndex index = ui->sourceFileView->currentIndex();
2483 if(index.isValid())
2485 QString systemRootPath;
2487 QDir systemRoot(MUtils::OS::known_folder(MUtils::OS::FOLDER_SYSTEMFOLDER));
2488 if(systemRoot.exists() && systemRoot.cdUp())
2490 systemRootPath = systemRoot.canonicalPath();
2493 if(!systemRootPath.isEmpty())
2495 QFileInfo explorer(QString("%1/explorer.exe").arg(systemRootPath));
2496 if(explorer.exists() && explorer.isFile())
2498 QProcess::execute(explorer.canonicalFilePath(), QStringList() << "/select," << QDir::toNativeSeparators(m_fileListModel->getFile(index).filePath()));
2499 return;
2502 else
2504 qWarning("SystemRoot directory could not be detected!");
2510 * Add all dropped files
2512 void MainWindow::handleDroppedFiles(void)
2514 ABORT_IF_BUSY;
2516 static const int MIN_COUNT = 16;
2517 const QString bannerText = tr("Loading dropped files or folders, please wait...");
2518 bool bUseBanner = false;
2520 SHOW_BANNER_CONDITIONALLY(bUseBanner, (m_droppedFileList->count() >= MIN_COUNT), bannerText);
2522 QStringList droppedFiles;
2523 while(!m_droppedFileList->isEmpty())
2525 QFileInfo file(m_droppedFileList->takeFirst().toLocalFile());
2526 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
2528 if(!file.exists())
2530 continue;
2533 if(file.isFile())
2535 qDebug("Dropped File: %s", MUTILS_UTF8(file.canonicalFilePath()));
2536 droppedFiles << file.canonicalFilePath();
2537 continue;
2540 if(file.isDir())
2542 qDebug("Dropped Folder: %s", MUTILS_UTF8(file.canonicalFilePath()));
2543 QFileInfoList list = QDir(file.canonicalFilePath()).entryInfoList(QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks);
2544 if(list.count() > 0)
2546 SHOW_BANNER_CONDITIONALLY(bUseBanner, (list.count() >= MIN_COUNT), bannerText);
2547 for(QFileInfoList::ConstIterator iter = list.constBegin(); iter != list.constEnd(); iter++)
2549 droppedFiles << (*iter).canonicalFilePath();
2552 else
2554 list = QDir(file.canonicalFilePath()).entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks);
2555 SHOW_BANNER_CONDITIONALLY(bUseBanner, (list.count() >= MIN_COUNT), bannerText);
2556 for(QFileInfoList::ConstIterator iter = list.constBegin(); iter != list.constEnd(); iter++)
2558 qDebug("Descending to Folder: %s", MUTILS_UTF8((*iter).canonicalFilePath()));
2559 m_droppedFileList->prepend(QUrl::fromLocalFile((*iter).canonicalFilePath()));
2565 if(bUseBanner)
2567 m_banner->close();
2570 if(!droppedFiles.isEmpty())
2572 addFiles(droppedFiles);
2577 * Add all pending files
2579 void MainWindow::handleDelayedFiles(void)
2581 m_delayedFileTimer->stop();
2583 if(m_delayedFileList->isEmpty())
2585 return;
2588 if(BANNER_VISIBLE)
2590 m_delayedFileTimer->start(5000);
2591 return;
2594 WITH_BLOCKED_SIGNALS(ui->tabWidget, setCurrentIndex, 0);
2595 tabPageChanged(ui->tabWidget->currentIndex(), true);
2597 QStringList selectedFiles;
2598 while(!m_delayedFileList->isEmpty())
2600 QFileInfo currentFile = QFileInfo(m_delayedFileList->takeFirst());
2601 if(!currentFile.exists() || !currentFile.isFile())
2603 continue;
2605 selectedFiles << currentFile.canonicalFilePath();
2608 addFiles(selectedFiles);
2612 * Export Meta tags to CSV file
2614 void MainWindow::exportCsvContextActionTriggered(void)
2616 TEMP_HIDE_DROPBOX
2618 QString selectedCsvFile;
2620 if(MUtils::GUI::themes_enabled())
2622 selectedCsvFile = QFileDialog::getSaveFileName(this, tr("Save CSV file"), m_settings->mostRecentInputPath(), QString("%1 (*.csv)").arg(tr("CSV File")));
2624 else
2626 QFileDialog dialog(this, tr("Save CSV file"));
2627 dialog.setFileMode(QFileDialog::AnyFile);
2628 dialog.setAcceptMode(QFileDialog::AcceptSave);
2629 dialog.setNameFilter(QString("%1 (*.csv)").arg(tr("CSV File")));
2630 dialog.setDirectory(m_settings->mostRecentInputPath());
2631 if(dialog.exec())
2633 selectedCsvFile = dialog.selectedFiles().first();
2637 if(!selectedCsvFile.isEmpty())
2639 m_settings->mostRecentInputPath(QFileInfo(selectedCsvFile).canonicalPath());
2640 switch(m_fileListModel->exportToCsv(selectedCsvFile))
2642 case FileListModel::CsvError_NoTags:
2643 QMessageBox::critical(this, tr("CSV Export"), NOBR(tr("Sorry, there are no meta tags that can be exported!")));
2644 break;
2645 case FileListModel::CsvError_FileOpen:
2646 QMessageBox::critical(this, tr("CSV Export"), NOBR(tr("Sorry, failed to open CSV file for writing!")));
2647 break;
2648 case FileListModel::CsvError_FileWrite:
2649 QMessageBox::critical(this, tr("CSV Export"), NOBR(tr("Sorry, failed to write to the CSV file!")));
2650 break;
2651 case FileListModel::CsvError_OK:
2652 QMessageBox::information(this, tr("CSV Export"), NOBR(tr("The CSV files was created successfully!")));
2653 break;
2654 default:
2655 qWarning("exportToCsv: Unknown return code!");
2663 * Import Meta tags from CSV file
2665 void MainWindow::importCsvContextActionTriggered(void)
2667 TEMP_HIDE_DROPBOX
2669 QString selectedCsvFile;
2671 if(MUtils::GUI::themes_enabled())
2673 selectedCsvFile = QFileDialog::getOpenFileName(this, tr("Open CSV file"), m_settings->mostRecentInputPath(), QString("%1 (*.csv)").arg(tr("CSV File")));
2675 else
2677 QFileDialog dialog(this, tr("Open CSV file"));
2678 dialog.setFileMode(QFileDialog::ExistingFile);
2679 dialog.setNameFilter(QString("%1 (*.csv)").arg(tr("CSV File")));
2680 dialog.setDirectory(m_settings->mostRecentInputPath());
2681 if(dialog.exec())
2683 selectedCsvFile = dialog.selectedFiles().first();
2687 if(!selectedCsvFile.isEmpty())
2689 m_settings->mostRecentInputPath(QFileInfo(selectedCsvFile).canonicalPath());
2690 switch(m_fileListModel->importFromCsv(this, selectedCsvFile))
2692 case FileListModel::CsvError_FileOpen:
2693 QMessageBox::critical(this, tr("CSV Import"), NOBR(tr("Sorry, failed to open CSV file for reading!")));
2694 break;
2695 case FileListModel::CsvError_FileRead:
2696 QMessageBox::critical(this, tr("CSV Import"), NOBR(tr("Sorry, failed to read from the CSV file!")));
2697 break;
2698 case FileListModel::CsvError_NoTags:
2699 QMessageBox::critical(this, tr("CSV Import"), NOBR(tr("Sorry, the CSV file does not contain any known fields!")));
2700 break;
2701 case FileListModel::CsvError_Incomplete:
2702 QMessageBox::warning(this, tr("CSV Import"), NOBR(tr("CSV file is incomplete. Not all files were updated!")));
2703 break;
2704 case FileListModel::CsvError_OK:
2705 QMessageBox::information(this, tr("CSV Import"), NOBR(tr("The CSV files was imported successfully!")));
2706 break;
2707 case FileListModel::CsvError_Aborted:
2708 /* User aborted, ignore! */
2709 break;
2710 default:
2711 qWarning("exportToCsv: Unknown return code!");
2718 * Show or hide Drag'n'Drop notice after model reset
2720 void MainWindow::sourceModelChanged(void)
2722 m_dropNoteLabel->setVisible(m_fileListModel->rowCount() <= 0);
2725 // =========================================================
2726 // Output folder slots
2727 // =========================================================
2730 * Output folder changed (mouse clicked)
2732 void MainWindow::outputFolderViewClicked(const QModelIndex &index)
2734 if(index.isValid() && (ui->outputFolderView->currentIndex() != index))
2736 ui->outputFolderView->setCurrentIndex(index);
2739 if(m_fileSystemModel && index.isValid())
2741 QString selectedDir = m_fileSystemModel->filePath(index);
2742 if(selectedDir.length() < 3) selectedDir.append(QDir::separator());
2743 ui->outputFolderLabel->setText(QDir::toNativeSeparators(selectedDir));
2744 ui->outputFolderLabel->setToolTip(ui->outputFolderLabel->text());
2745 m_settings->outputDir(selectedDir);
2747 else
2749 ui->outputFolderLabel->setText(QDir::toNativeSeparators(m_settings->outputDir()));
2750 ui->outputFolderLabel->setToolTip(ui->outputFolderLabel->text());
2755 * Output folder changed (mouse moved)
2757 void MainWindow::outputFolderViewMoved(const QModelIndex &index)
2759 if(QApplication::mouseButtons() & Qt::LeftButton)
2761 outputFolderViewClicked(index);
2766 * Goto desktop button
2768 void MainWindow::gotoDesktopButtonClicked(void)
2770 if(!m_fileSystemModel)
2772 qWarning("File system model not initialized yet!");
2773 return;
2776 QString desktopPath = QDesktopServices::storageLocation(QDesktopServices::DesktopLocation);
2778 if(!desktopPath.isEmpty() && QDir(desktopPath).exists())
2780 ui->outputFolderView->setCurrentIndex(m_fileSystemModel->index(desktopPath));
2781 outputFolderViewClicked(ui->outputFolderView->currentIndex());
2782 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2784 else
2786 ui->buttonGotoDesktop->setEnabled(false);
2791 * Goto home folder button
2793 void MainWindow::gotoHomeFolderButtonClicked(void)
2795 if(!m_fileSystemModel)
2797 qWarning("File system model not initialized yet!");
2798 return;
2801 QString homePath = QDesktopServices::storageLocation(QDesktopServices::HomeLocation);
2803 if(!homePath.isEmpty() && QDir(homePath).exists())
2805 ui->outputFolderView->setCurrentIndex(m_fileSystemModel->index(homePath));
2806 outputFolderViewClicked(ui->outputFolderView->currentIndex());
2807 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2809 else
2811 ui->buttonGotoHome->setEnabled(false);
2816 * Goto music folder button
2818 void MainWindow::gotoMusicFolderButtonClicked(void)
2820 if(!m_fileSystemModel)
2822 qWarning("File system model not initialized yet!");
2823 return;
2826 QString musicPath = QDesktopServices::storageLocation(QDesktopServices::MusicLocation);
2828 if(!musicPath.isEmpty() && QDir(musicPath).exists())
2830 ui->outputFolderView->setCurrentIndex(m_fileSystemModel->index(musicPath));
2831 outputFolderViewClicked(ui->outputFolderView->currentIndex());
2832 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2834 else
2836 ui->buttonGotoMusic->setEnabled(false);
2841 * Goto music favorite output folder
2843 void MainWindow::gotoFavoriteFolder(void)
2845 if(!m_fileSystemModel)
2847 qWarning("File system model not initialized yet!");
2848 return;
2851 QAction *item = dynamic_cast<QAction*>(QObject::sender());
2853 if(item)
2855 QDir path(item->data().toString());
2856 if(path.exists())
2858 ui->outputFolderView->setCurrentIndex(m_fileSystemModel->index(path.canonicalPath()));
2859 outputFolderViewClicked(ui->outputFolderView->currentIndex());
2860 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2862 else
2864 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
2865 m_outputFolderFavoritesMenu->removeAction(item);
2866 item->deleteLater();
2872 * Make folder button
2874 void MainWindow::makeFolderButtonClicked(void)
2876 ABORT_IF_BUSY;
2878 if(!m_fileSystemModel)
2880 qWarning("File system model not initialized yet!");
2881 return;
2884 QDir basePath(m_fileSystemModel->fileInfo(ui->outputFolderView->currentIndex()).absoluteFilePath());
2885 QString suggestedName = tr("New Folder");
2887 if(!m_metaData->artist().isEmpty() && !m_metaData->album().isEmpty())
2889 suggestedName = QString("%1 - %2").arg(m_metaData->artist(),m_metaData->album());
2891 else if(!m_metaData->artist().isEmpty())
2893 suggestedName = m_metaData->artist();
2895 else if(!m_metaData->album().isEmpty())
2897 suggestedName =m_metaData->album();
2899 else
2901 for(int i = 0; i < m_fileListModel->rowCount(); i++)
2903 const AudioFileModel &audioFile = m_fileListModel->getFile(m_fileListModel->index(i, 0));
2904 const AudioFileModel_MetaInfo &fileMetaInfo = audioFile.metaInfo();
2906 if(!fileMetaInfo.album().isEmpty() || !fileMetaInfo.artist().isEmpty())
2908 if(!fileMetaInfo.artist().isEmpty() && !fileMetaInfo.album().isEmpty())
2910 suggestedName = QString("%1 - %2").arg(fileMetaInfo.artist(), fileMetaInfo.album());
2912 else if(!fileMetaInfo.artist().isEmpty())
2914 suggestedName = fileMetaInfo.artist();
2916 else if(!fileMetaInfo.album().isEmpty())
2918 suggestedName = fileMetaInfo.album();
2920 break;
2925 suggestedName = MUtils::clean_file_name(suggestedName);
2927 while(true)
2929 bool bApplied = false;
2930 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();
2932 if(bApplied)
2934 folderName = MUtils::clean_file_path(folderName.simplified());
2936 if(folderName.isEmpty())
2938 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
2939 continue;
2942 int i = 1;
2943 QString newFolder = folderName;
2945 while(basePath.exists(newFolder))
2947 newFolder = QString(folderName).append(QString().sprintf(" (%d)", ++i));
2950 if(basePath.mkpath(newFolder))
2952 QDir createdDir = basePath;
2953 if(createdDir.cd(newFolder))
2955 QModelIndex newIndex = m_fileSystemModel->index(createdDir.canonicalPath());
2956 ui->outputFolderView->setCurrentIndex(newIndex);
2957 outputFolderViewClicked(newIndex);
2958 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2961 else
2963 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!")));
2966 break;
2971 * Output to source dir changed
2973 void MainWindow::saveToSourceFolderChanged(void)
2975 m_settings->outputToSourceDir(ui->saveToSourceFolderCheckBox->isChecked());
2979 * Prepend relative source file path to output file name changed
2981 void MainWindow::prependRelativePathChanged(void)
2983 m_settings->prependRelativeSourcePath(ui->prependRelativePathCheckBox->isChecked());
2987 * Show context menu for output folder
2989 void MainWindow::outputFolderContextMenu(const QPoint &pos)
2991 QAbstractScrollArea *scrollArea = dynamic_cast<QAbstractScrollArea*>(QObject::sender());
2992 QWidget *sender = scrollArea ? scrollArea->viewport() : dynamic_cast<QWidget*>(QObject::sender());
2994 if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0)
2996 m_outputFolderContextMenu->popup(sender->mapToGlobal(pos));
3001 * Show selected folder in explorer
3003 void MainWindow::showFolderContextActionTriggered(void)
3005 if(!m_fileSystemModel)
3007 qWarning("File system model not initialized yet!");
3008 return;
3011 QString path = QDir::toNativeSeparators(m_fileSystemModel->filePath(ui->outputFolderView->currentIndex()));
3012 if(!path.endsWith(QDir::separator())) path.append(QDir::separator());
3013 MUtils::OS::shell_open(this, path, true);
3017 * Refresh the directory outline
3019 void MainWindow::refreshFolderContextActionTriggered(void)
3021 //force re-initialization
3022 QTimer::singleShot(0, this, SLOT(initOutputFolderModel()));
3026 * Go one directory up
3028 void MainWindow::goUpFolderContextActionTriggered(void)
3030 QModelIndex current = ui->outputFolderView->currentIndex();
3031 if(current.isValid())
3033 QModelIndex parent = current.parent();
3034 if(parent.isValid())
3037 ui->outputFolderView->setCurrentIndex(parent);
3038 outputFolderViewClicked(parent);
3040 else
3042 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN);
3044 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
3049 * Add current folder to favorites
3051 void MainWindow::addFavoriteFolderActionTriggered(void)
3053 QString path = m_fileSystemModel->filePath(ui->outputFolderView->currentIndex());
3054 QStringList favorites = m_settings->favoriteOutputFolders().split("|", QString::SkipEmptyParts);
3056 if(!favorites.contains(path, Qt::CaseInsensitive))
3058 favorites.append(path);
3059 while(favorites.count() > 6) favorites.removeFirst();
3061 else
3063 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN);
3066 m_settings->favoriteOutputFolders(favorites.join("|"));
3067 refreshFavorites();
3071 * Output folder edit finished
3073 void MainWindow::outputFolderEditFinished(void)
3075 if(ui->outputFolderEdit->isHidden())
3077 return; //Not currently in edit mode!
3080 bool ok = false;
3082 QString text = QDir::fromNativeSeparators(ui->outputFolderEdit->text().trimmed());
3083 while(text.startsWith('"') || text.startsWith('/')) text = text.right(text.length() - 1).trimmed();
3084 while(text.endsWith('"') || text.endsWith('/')) text = text.left(text.length() - 1).trimmed();
3086 static const char *str = "?*<>|\"";
3087 for(size_t i = 0; str[i]; i++) text.replace(str[i], "_");
3089 if(!((text.length() >= 2) && text.at(0).isLetter() && text.at(1) == QChar(':')))
3091 text = QString("%1/%2").arg(QDir::fromNativeSeparators(ui->outputFolderLabel->text()), text);
3094 if(text.length() == 2) text += "/"; /* "X:" => "X:/" */
3096 while(text.length() > 2)
3098 QFileInfo info(text);
3099 if(info.exists() && info.isDir())
3101 QModelIndex index = m_fileSystemModel->index(QFileInfo(info.canonicalFilePath()).absoluteFilePath());
3102 if(index.isValid())
3104 ok = true;
3105 ui->outputFolderView->setCurrentIndex(index);
3106 outputFolderViewClicked(index);
3107 break;
3110 else if(info.exists() && info.isFile())
3112 QModelIndex index = m_fileSystemModel->index(QFileInfo(info.canonicalPath()).absoluteFilePath());
3113 if(index.isValid())
3115 ok = true;
3116 ui->outputFolderView->setCurrentIndex(index);
3117 outputFolderViewClicked(index);
3118 break;
3122 text = text.left(text.length() - 1).trimmed();
3125 ui->outputFolderEdit->setVisible(false);
3126 ui->outputFolderLabel->setVisible(true);
3127 ui->outputFolderView->setEnabled(true);
3129 if(!ok) MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
3130 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
3134 * Initialize file system model
3136 void MainWindow::initOutputFolderModel(void)
3138 if(m_outputFolderNoteBox->isHidden())
3140 m_outputFolderNoteBox->show();
3141 m_outputFolderNoteBox->repaint();
3142 m_outputFolderViewInitCounter = 4;
3144 if(m_fileSystemModel)
3146 SET_MODEL(ui->outputFolderView, NULL);
3147 MUTILS_DELETE(m_fileSystemModel);
3148 ui->outputFolderView->repaint();
3151 if(m_fileSystemModel = new QFileSystemModelEx())
3153 m_fileSystemModel->installEventFilter(this);
3154 connect(m_fileSystemModel, SIGNAL(directoryLoaded(QString)), this, SLOT(outputFolderDirectoryLoaded(QString)));
3155 connect(m_fileSystemModel, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(outputFolderRowsInserted(QModelIndex,int,int)));
3157 SET_MODEL(ui->outputFolderView, m_fileSystemModel);
3158 ui->outputFolderView->header()->setStretchLastSection(true);
3159 ui->outputFolderView->header()->hideSection(1);
3160 ui->outputFolderView->header()->hideSection(2);
3161 ui->outputFolderView->header()->hideSection(3);
3163 m_fileSystemModel->setRootPath("");
3164 QModelIndex index = m_fileSystemModel->index(m_settings->outputDir());
3165 if(index.isValid()) ui->outputFolderView->setCurrentIndex(index);
3166 outputFolderViewClicked(ui->outputFolderView->currentIndex());
3169 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
3170 QTimer::singleShot(125, this, SLOT(initOutputFolderModel_doAsync()));
3175 * Initialize file system model (do NOT call this one directly!)
3177 void MainWindow::initOutputFolderModel_doAsync(void)
3179 if(m_outputFolderViewInitCounter > 0)
3181 m_outputFolderViewInitCounter--;
3182 QTimer::singleShot(125, this, SLOT(initOutputFolderModel_doAsync()));
3184 else
3186 QTimer::singleShot(125, m_outputFolderNoteBox, SLOT(hide()));
3187 ui->outputFolderView->setFocus();
3192 * Center current folder in view
3194 void MainWindow::centerOutputFolderModel(void)
3196 if(ui->outputFolderView->isVisible())
3198 centerOutputFolderModel_doAsync();
3199 QTimer::singleShot(125, this, SLOT(centerOutputFolderModel_doAsync()));
3204 * Center current folder in view (do NOT call this one directly!)
3206 void MainWindow::centerOutputFolderModel_doAsync(void)
3208 if(ui->outputFolderView->isVisible())
3210 m_outputFolderViewCentering = true;
3211 const QModelIndex index = ui->outputFolderView->currentIndex();
3212 ui->outputFolderView->scrollTo(index, QAbstractItemView::PositionAtCenter);
3213 ui->outputFolderView->setFocus();
3218 * File system model asynchronously loaded a dir
3220 void MainWindow::outputFolderDirectoryLoaded(const QString &path)
3222 if(m_outputFolderViewCentering)
3224 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
3229 * File system model inserted new items
3231 void MainWindow::outputFolderRowsInserted(const QModelIndex &parent, int start, int end)
3233 if(m_outputFolderViewCentering)
3235 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
3240 * Directory view item was expanded by user
3242 void MainWindow::outputFolderItemExpanded(const QModelIndex &item)
3244 //We need to stop centering as soon as the user has expanded an item manually!
3245 m_outputFolderViewCentering = false;
3249 * View event for output folder control occurred
3251 void MainWindow::outputFolderViewEventOccurred(QWidget *sender, QEvent *event)
3253 switch(event->type())
3255 case QEvent::Enter:
3256 case QEvent::Leave:
3257 case QEvent::KeyPress:
3258 case QEvent::KeyRelease:
3259 case QEvent::FocusIn:
3260 case QEvent::FocusOut:
3261 case QEvent::TouchEnd:
3262 outputFolderViewClicked(ui->outputFolderView->currentIndex());
3263 break;
3268 * Mouse event for output folder control occurred
3270 void MainWindow::outputFolderMouseEventOccurred(QWidget *sender, QEvent *event)
3272 QMouseEvent *mouseEvent = dynamic_cast<QMouseEvent*>(event);
3273 QPoint pos = (mouseEvent) ? mouseEvent->pos() : QPoint();
3275 if(sender == ui->outputFolderLabel)
3277 switch(event->type())
3279 case QEvent::MouseButtonPress:
3280 if(mouseEvent && (mouseEvent->button() == Qt::LeftButton))
3282 QString path = ui->outputFolderLabel->text();
3283 if(!path.endsWith(QDir::separator())) path.append(QDir::separator());
3284 MUtils::OS::shell_open(this, path, true);
3286 break;
3287 case QEvent::Enter:
3288 ui->outputFolderLabel->setForegroundRole(QPalette::Link);
3289 break;
3290 case QEvent::Leave:
3291 ui->outputFolderLabel->setForegroundRole(QPalette::WindowText);
3292 break;
3296 if((sender == ui->outputFoldersFovoritesLabel) || (sender == ui->outputFoldersEditorLabel) || (sender == ui->outputFoldersGoUpLabel))
3298 const type_info &styleType = typeid(*qApp->style());
3299 if((typeid(QPlastiqueStyle) == styleType) || (typeid(QWindowsStyle) == styleType))
3301 switch(event->type())
3303 case QEvent::Enter:
3304 dynamic_cast<QLabel*>(sender)->setFrameShadow(ui->outputFolderView->isEnabled() ? QFrame::Raised : QFrame::Plain);
3305 break;
3306 case QEvent::MouseButtonPress:
3307 dynamic_cast<QLabel*>(sender)->setFrameShadow(ui->outputFolderView->isEnabled() ? QFrame::Sunken : QFrame::Plain);
3308 break;
3309 case QEvent::MouseButtonRelease:
3310 dynamic_cast<QLabel*>(sender)->setFrameShadow(ui->outputFolderView->isEnabled() ? QFrame::Raised : QFrame::Plain);
3311 break;
3312 case QEvent::Leave:
3313 dynamic_cast<QLabel*>(sender)->setFrameShadow(ui->outputFolderView->isEnabled() ? QFrame::Plain : QFrame::Plain);
3314 break;
3317 else
3319 dynamic_cast<QLabel*>(sender)->setFrameShadow(QFrame::Plain);
3322 if((event->type() == QEvent::MouseButtonRelease) && ui->outputFolderView->isEnabled() && (mouseEvent))
3324 if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0 && mouseEvent->button() != Qt::MidButton)
3326 if(sender == ui->outputFoldersFovoritesLabel)
3328 m_outputFolderFavoritesMenu->popup(sender->mapToGlobal(pos));
3330 else if(sender == ui->outputFoldersEditorLabel)
3332 ui->outputFolderView->setEnabled(false);
3333 ui->outputFolderLabel->setVisible(false);
3334 ui->outputFolderEdit->setVisible(true);
3335 ui->outputFolderEdit->setText(ui->outputFolderLabel->text());
3336 ui->outputFolderEdit->selectAll();
3337 ui->outputFolderEdit->setFocus();
3339 else if(sender == ui->outputFoldersGoUpLabel)
3341 QTimer::singleShot(0, this, SLOT(goUpFolderContextActionTriggered()));
3343 else
3345 MUTILS_THROW("Oups, this is not supposed to happen!");
3352 // =========================================================
3353 // Metadata tab slots
3354 // =========================================================
3357 * Edit meta button clicked
3359 void MainWindow::editMetaButtonClicked(void)
3361 ABORT_IF_BUSY;
3363 const QModelIndex index = ui->metaDataView->currentIndex();
3365 if(index.isValid())
3367 m_metaInfoModel->editItem(index, this);
3369 if(index.row() == 4)
3371 m_settings->metaInfoPosition(m_metaData->position());
3377 * Reset meta button clicked
3379 void MainWindow::clearMetaButtonClicked(void)
3381 ABORT_IF_BUSY;
3382 m_metaInfoModel->clearData();
3386 * Meta tags enabled changed
3388 void MainWindow::metaTagsEnabledChanged(void)
3390 m_settings->writeMetaTags(ui->writeMetaDataCheckBox->isChecked());
3394 * Playlist enabled changed
3396 void MainWindow::playlistEnabledChanged(void)
3398 m_settings->createPlaylist(ui->generatePlaylistCheckBox->isChecked());
3401 // =========================================================
3402 // Compression tab slots
3403 // =========================================================
3406 * Update encoder
3408 void MainWindow::updateEncoder(int id)
3410 /*qWarning("\nupdateEncoder(%d)", id);*/
3412 m_settings->compressionEncoder(id);
3413 const AbstractEncoderInfo *info = EncoderRegistry::getEncoderInfo(id);
3415 //Update UI controls
3416 ui->radioButtonModeQuality ->setEnabled(info->isModeSupported(SettingsModel::VBRMode));
3417 ui->radioButtonModeAverageBitrate->setEnabled(info->isModeSupported(SettingsModel::ABRMode));
3418 ui->radioButtonConstBitrate ->setEnabled(info->isModeSupported(SettingsModel::CBRMode));
3420 //Initialize checkbox state
3421 if(ui->radioButtonModeQuality->isEnabled()) ui->radioButtonModeQuality->setChecked(true);
3422 else if(ui->radioButtonModeAverageBitrate->isEnabled()) ui->radioButtonModeAverageBitrate->setChecked(true);
3423 else if(ui->radioButtonConstBitrate->isEnabled()) ui->radioButtonConstBitrate->setChecked(true);
3424 else MUTILS_THROW("It appears that the encoder does not support *any* RC mode!");
3426 //Apply current RC mode
3427 const int currentRCMode = EncoderRegistry::loadEncoderMode(m_settings, id);
3428 switch(currentRCMode)
3430 case SettingsModel::VBRMode: if(ui->radioButtonModeQuality->isEnabled()) ui->radioButtonModeQuality->setChecked(true); break;
3431 case SettingsModel::ABRMode: if(ui->radioButtonModeAverageBitrate->isEnabled()) ui->radioButtonModeAverageBitrate->setChecked(true); break;
3432 case SettingsModel::CBRMode: if(ui->radioButtonConstBitrate->isEnabled()) ui->radioButtonConstBitrate->setChecked(true); break;
3433 default: MUTILS_THROW("updateEncoder(): Unknown rc-mode encountered!");
3436 //Display encoder description
3437 if(const char* description = info->description())
3439 ui->labelEncoderInfo->setVisible(true);
3440 ui->labelEncoderInfo->setText(tr("Current Encoder: %1").arg(QString::fromUtf8(description)));
3442 else
3444 ui->labelEncoderInfo->setVisible(false);
3447 //Update RC mode!
3448 updateRCMode(m_modeButtonGroup->checkedId());
3452 * Update rate-control mode
3454 void MainWindow::updateRCMode(int id)
3456 /*qWarning("updateRCMode(%d)", id);*/
3458 //Store new RC mode
3459 const int currentEncoder = m_encoderButtonGroup->checkedId();
3460 EncoderRegistry::saveEncoderMode(m_settings, currentEncoder, id);
3462 //Fetch encoder info
3463 const AbstractEncoderInfo *info = EncoderRegistry::getEncoderInfo(currentEncoder);
3464 const int valueCount = info->valueCount(id);
3466 //Sanity check
3467 if(!info->isModeSupported(id))
3469 qWarning("Attempting to use an unsupported RC mode (%d) with current encoder (%d)!", id, currentEncoder);
3470 ui->labelBitrate->setText("(ERROR)");
3471 return;
3474 //Update slider min/max values
3475 if(valueCount > 0)
3477 WITH_BLOCKED_SIGNALS(ui->sliderBitrate, setEnabled, true);
3478 WITH_BLOCKED_SIGNALS(ui->sliderBitrate, setMinimum, 0);
3479 WITH_BLOCKED_SIGNALS(ui->sliderBitrate, setMaximum, valueCount-1);
3481 else
3483 WITH_BLOCKED_SIGNALS(ui->sliderBitrate, setEnabled, false);
3484 WITH_BLOCKED_SIGNALS(ui->sliderBitrate, setMinimum, 0);
3485 WITH_BLOCKED_SIGNALS(ui->sliderBitrate, setMaximum, 2);
3488 //Now update bitrate/quality value!
3489 if(valueCount > 0)
3491 const int currentValue = EncoderRegistry::loadEncoderValue(m_settings, currentEncoder, id);
3492 ui->sliderBitrate->setValue(qBound(0, currentValue, valueCount-1));
3493 updateBitrate(qBound(0, currentValue, valueCount-1));
3495 else
3497 ui->sliderBitrate->setValue(1);
3498 updateBitrate(0);
3503 * Update bitrate
3505 void MainWindow::updateBitrate(int value)
3507 /*qWarning("updateBitrate(%d)", value);*/
3509 //Load current encoder and RC mode
3510 const int currentEncoder = m_encoderButtonGroup->checkedId();
3511 const int currentRCMode = m_modeButtonGroup->checkedId();
3513 //Fetch encoder info
3514 const AbstractEncoderInfo *info = EncoderRegistry::getEncoderInfo(currentEncoder);
3515 const int valueCount = info->valueCount(currentRCMode);
3517 //Sanity check
3518 if(!info->isModeSupported(currentRCMode))
3520 qWarning("Attempting to use an unsupported RC mode (%d) with current encoder (%d)!", currentRCMode, currentEncoder);
3521 ui->labelBitrate->setText("(ERROR)");
3522 return;
3525 //Store new bitrate value
3526 if(valueCount > 0)
3528 EncoderRegistry::saveEncoderValue(m_settings, currentEncoder, currentRCMode, qBound(0, value, valueCount-1));
3531 //Update bitrate value
3532 const int displayValue = (valueCount > 0) ? info->valueAt(currentRCMode, qBound(0, value, valueCount-1)) : INT_MAX;
3533 switch(info->valueType(currentRCMode))
3535 case AbstractEncoderInfo::TYPE_BITRATE:
3536 ui->labelBitrate->setText(QString("%1 kbps").arg(QString::number(displayValue)));
3537 break;
3538 case AbstractEncoderInfo::TYPE_APPROX_BITRATE:
3539 ui->labelBitrate->setText(QString("&asymp; %1 kbps").arg(QString::number(displayValue)));
3540 break;
3541 case AbstractEncoderInfo::TYPE_QUALITY_LEVEL_INT:
3542 ui->labelBitrate->setText(tr("Quality Level %1").arg(QString::number(displayValue)));
3543 break;
3544 case AbstractEncoderInfo::TYPE_QUALITY_LEVEL_FLT:
3545 ui->labelBitrate->setText(tr("Quality Level %1").arg(QString().sprintf("%.2f", double(displayValue)/100.0)));
3546 break;
3547 case AbstractEncoderInfo::TYPE_COMPRESSION_LEVEL:
3548 ui->labelBitrate->setText(tr("Compression %1").arg(QString::number(displayValue)));
3549 break;
3550 case AbstractEncoderInfo::TYPE_UNCOMPRESSED:
3551 ui->labelBitrate->setText(tr("Uncompressed"));
3552 break;
3553 default:
3554 MUTILS_THROW("Unknown display value type encountered!");
3555 break;
3560 * Event for compression tab occurred
3562 void MainWindow::compressionTabEventOccurred(QWidget *sender, QEvent *event)
3564 static const QUrl helpUrl("http://lamexp.sourceforge.net/doc/FAQ.html#054010d9");
3566 if((sender == ui->labelCompressionHelp) && (event->type() == QEvent::MouseButtonPress))
3568 QDesktopServices::openUrl(helpUrl);
3570 else if((sender == ui->labelResetEncoders) && (event->type() == QEvent::MouseButtonPress))
3572 PLAY_SOUND_OPTIONAL("blast", true);
3573 EncoderRegistry::resetAllEncoders(m_settings);
3574 m_settings->compressionEncoder(SettingsModel::MP3Encoder);
3575 ui->radioButtonEncoderMP3->setChecked(true);
3576 QTimer::singleShot(0, this, SLOT(updateEncoder()));
3580 // =========================================================
3581 // Advanced option slots
3582 // =========================================================
3585 * Lame algorithm quality changed
3587 void MainWindow::updateLameAlgoQuality(int value)
3589 QString text;
3591 switch(value)
3593 case 3:
3594 text = tr("Best Quality (Slow)");
3595 break;
3596 case 2:
3597 text = tr("High Quality (Recommended)");
3598 break;
3599 case 1:
3600 text = tr("Acceptable Quality (Fast)");
3601 break;
3602 case 0:
3603 text = tr("Poor Quality (Very Fast)");
3604 break;
3607 if(!text.isEmpty())
3609 m_settings->lameAlgoQuality(value);
3610 ui->labelLameAlgoQuality->setText(text);
3613 bool warning = (value == 0), notice = (value == 3);
3614 ui->labelLameAlgoQualityWarning->setVisible(warning);
3615 ui->labelLameAlgoQualityWarningIcon->setVisible(warning);
3616 ui->labelLameAlgoQualityNotice->setVisible(notice);
3617 ui->labelLameAlgoQualityNoticeIcon->setVisible(notice);
3618 ui->labelLameAlgoQualitySpacer->setVisible(warning || notice);
3622 * Bitrate management endabled/disabled
3624 void MainWindow::bitrateManagementEnabledChanged(bool checked)
3626 m_settings->bitrateManagementEnabled(checked);
3630 * Minimum bitrate has changed
3632 void MainWindow::bitrateManagementMinChanged(int value)
3634 if(value > ui->spinBoxBitrateManagementMax->value())
3636 ui->spinBoxBitrateManagementMin->setValue(ui->spinBoxBitrateManagementMax->value());
3637 m_settings->bitrateManagementMinRate(ui->spinBoxBitrateManagementMax->value());
3639 else
3641 m_settings->bitrateManagementMinRate(value);
3646 * Maximum bitrate has changed
3648 void MainWindow::bitrateManagementMaxChanged(int value)
3650 if(value < ui->spinBoxBitrateManagementMin->value())
3652 ui->spinBoxBitrateManagementMax->setValue(ui->spinBoxBitrateManagementMin->value());
3653 m_settings->bitrateManagementMaxRate(ui->spinBoxBitrateManagementMin->value());
3655 else
3657 m_settings->bitrateManagementMaxRate(value);
3662 * Channel mode has changed
3664 void MainWindow::channelModeChanged(int value)
3666 if(value >= 0) m_settings->lameChannelMode(value);
3670 * Sampling rate has changed
3672 void MainWindow::samplingRateChanged(int value)
3674 if(value >= 0) m_settings->samplingRate(value);
3678 * Nero AAC 2-Pass mode changed
3680 void MainWindow::neroAAC2PassChanged(bool checked)
3682 m_settings->neroAACEnable2Pass(checked);
3686 * Nero AAC profile mode changed
3688 void MainWindow::neroAACProfileChanged(int value)
3690 if(value >= 0) m_settings->aacEncProfile(value);
3694 * Aften audio coding mode changed
3696 void MainWindow::aftenCodingModeChanged(int value)
3698 if(value >= 0) m_settings->aftenAudioCodingMode(value);
3702 * Aften DRC mode changed
3704 void MainWindow::aftenDRCModeChanged(int value)
3706 if(value >= 0) m_settings->aftenDynamicRangeCompression(value);
3710 * Aften exponent search size changed
3712 void MainWindow::aftenSearchSizeChanged(int value)
3714 if(value >= 0) m_settings->aftenExponentSearchSize(value);
3718 * Aften fast bit allocation changed
3720 void MainWindow::aftenFastAllocationChanged(bool checked)
3722 m_settings->aftenFastBitAllocation(checked);
3727 * Opus encoder settings changed
3729 void MainWindow::opusSettingsChanged(void)
3731 m_settings->opusFramesize(ui->comboBoxOpusFramesize->currentIndex());
3732 m_settings->opusComplexity(ui->spinBoxOpusComplexity->value());
3733 m_settings->opusDisableResample(ui->checkBoxOpusDisableResample->isChecked());
3737 * Normalization filter enabled changed
3739 void MainWindow::normalizationEnabledChanged(bool checked)
3741 m_settings->normalizationFilterEnabled(checked);
3745 * Normalization max. volume changed
3747 void MainWindow::normalizationMaxVolumeChanged(double value)
3749 m_settings->normalizationFilterMaxVolume(static_cast<int>(value * 100.0));
3753 * Normalization equalization mode changed
3755 void MainWindow::normalizationModeChanged(int mode)
3757 m_settings->normalizationFilterEQMode(mode);
3761 * Tone adjustment has changed (Bass)
3763 void MainWindow::toneAdjustBassChanged(double value)
3765 m_settings->toneAdjustBass(static_cast<int>(value * 100.0));
3766 ui->spinBoxToneAdjustBass->setPrefix((value > 0) ? "+" : QString());
3770 * Tone adjustment has changed (Treble)
3772 void MainWindow::toneAdjustTrebleChanged(double value)
3774 m_settings->toneAdjustTreble(static_cast<int>(value * 100.0));
3775 ui->spinBoxToneAdjustTreble->setPrefix((value > 0) ? "+" : QString());
3779 * Tone adjustment has been reset
3781 void MainWindow::toneAdjustTrebleReset(void)
3783 ui->spinBoxToneAdjustBass->setValue(m_settings->toneAdjustBassDefault());
3784 ui->spinBoxToneAdjustTreble->setValue(m_settings->toneAdjustTrebleDefault());
3785 toneAdjustBassChanged(ui->spinBoxToneAdjustBass->value());
3786 toneAdjustTrebleChanged(ui->spinBoxToneAdjustTreble->value());
3790 * Custom encoder parameters changed
3792 void MainWindow::customParamsChanged(void)
3794 ui->lineEditCustomParamLAME->setText(ui->lineEditCustomParamLAME->text().simplified());
3795 ui->lineEditCustomParamOggEnc->setText(ui->lineEditCustomParamOggEnc->text().simplified());
3796 ui->lineEditCustomParamNeroAAC->setText(ui->lineEditCustomParamNeroAAC->text().simplified());
3797 ui->lineEditCustomParamFLAC->setText(ui->lineEditCustomParamFLAC->text().simplified());
3798 ui->lineEditCustomParamAften->setText(ui->lineEditCustomParamAften->text().simplified());
3799 ui->lineEditCustomParamOpus->setText(ui->lineEditCustomParamOpus->text().simplified());
3801 bool customParamsUsed = false;
3802 if(!ui->lineEditCustomParamLAME->text().isEmpty()) customParamsUsed = true;
3803 if(!ui->lineEditCustomParamOggEnc->text().isEmpty()) customParamsUsed = true;
3804 if(!ui->lineEditCustomParamNeroAAC->text().isEmpty()) customParamsUsed = true;
3805 if(!ui->lineEditCustomParamFLAC->text().isEmpty()) customParamsUsed = true;
3806 if(!ui->lineEditCustomParamAften->text().isEmpty()) customParamsUsed = true;
3807 if(!ui->lineEditCustomParamOpus->text().isEmpty()) customParamsUsed = true;
3809 ui->labelCustomParamsIcon->setVisible(customParamsUsed);
3810 ui->labelCustomParamsText->setVisible(customParamsUsed);
3811 ui->labelCustomParamsSpacer->setVisible(customParamsUsed);
3813 EncoderRegistry::saveEncoderCustomParams(m_settings, SettingsModel::MP3Encoder, ui->lineEditCustomParamLAME->text());
3814 EncoderRegistry::saveEncoderCustomParams(m_settings, SettingsModel::VorbisEncoder, ui->lineEditCustomParamOggEnc->text());
3815 EncoderRegistry::saveEncoderCustomParams(m_settings, SettingsModel::AACEncoder, ui->lineEditCustomParamNeroAAC->text());
3816 EncoderRegistry::saveEncoderCustomParams(m_settings, SettingsModel::FLACEncoder, ui->lineEditCustomParamFLAC->text());
3817 EncoderRegistry::saveEncoderCustomParams(m_settings, SettingsModel::AC3Encoder, ui->lineEditCustomParamAften->text());
3818 EncoderRegistry::saveEncoderCustomParams(m_settings, SettingsModel::OpusEncoder, ui->lineEditCustomParamOpus->text());
3822 * Rename output files enabled changed
3824 void MainWindow::renameOutputEnabledChanged(bool checked)
3826 m_settings->renameOutputFilesEnabled(checked);
3830 * Rename output files patterm changed
3832 void MainWindow::renameOutputPatternChanged(void)
3834 QString temp = ui->lineEditRenamePattern->text().simplified();
3835 ui->lineEditRenamePattern->setText(temp.isEmpty() ? m_settings->renameOutputFilesPatternDefault() : temp);
3836 m_settings->renameOutputFilesPattern(ui->lineEditRenamePattern->text());
3840 * Rename output files patterm changed
3842 void MainWindow::renameOutputPatternChanged(const QString &text, bool silent)
3844 QString pattern(text.simplified());
3846 pattern.replace("<BaseName>", "The_White_Stripes_-_Fell_In_Love_With_A_Girl", Qt::CaseInsensitive);
3847 pattern.replace("<TrackNo>", "04", Qt::CaseInsensitive);
3848 pattern.replace("<Title>", "Fell In Love With A Girl", Qt::CaseInsensitive);
3849 pattern.replace("<Artist>", "The White Stripes", Qt::CaseInsensitive);
3850 pattern.replace("<Album>", "White Blood Cells", Qt::CaseInsensitive);
3851 pattern.replace("<Year>", "2001", Qt::CaseInsensitive);
3852 pattern.replace("<Comment>", "Encoded by LameXP", Qt::CaseInsensitive);
3854 const QString patternClean = MUtils::clean_file_name(pattern);
3856 if(pattern.compare(patternClean))
3858 if(ui->lineEditRenamePattern->palette().color(QPalette::Text) != Qt::red)
3860 if(!silent) MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
3861 SET_TEXT_COLOR(ui->lineEditRenamePattern, Qt::red);
3864 else
3866 if(ui->lineEditRenamePattern->palette() != QPalette())
3868 if(!silent) MUtils::Sound::beep(MUtils::Sound::BEEP_NFO);
3869 ui->lineEditRenamePattern->setPalette(QPalette());
3873 ui->labelRanameExample->setText(patternClean);
3877 * Show list of rename macros
3879 void MainWindow::showRenameMacros(const QString &text)
3881 if(text.compare("reset", Qt::CaseInsensitive) == 0)
3883 ui->lineEditRenamePattern->setText(m_settings->renameOutputFilesPatternDefault());
3884 return;
3887 const QString format = QString("<tr><td><tt>&lt;%1&gt;</tt></td><td>&nbsp;&nbsp;</td><td>%2</td></tr>");
3889 QString message = QString("<table>");
3890 message += QString(format).arg("BaseName", tr("File name without extension"));
3891 message += QString(format).arg("TrackNo", tr("Track number with leading zero"));
3892 message += QString(format).arg("Title", tr("Track title"));
3893 message += QString(format).arg("Artist", tr("Artist name"));
3894 message += QString(format).arg("Album", tr("Album name"));
3895 message += QString(format).arg("Year", tr("Year with (at least) four digits"));
3896 message += QString(format).arg("Comment", tr("Comment"));
3897 message += "</table><br><br>";
3898 message += QString("%1<br>").arg(tr("Characters forbidden in file names:"));
3899 message += "<b><tt>\\ / : * ? &lt; &gt; |<br>";
3901 QMessageBox::information(this, tr("Rename Macros"), message, tr("Discard"));
3904 void MainWindow::forceStereoDownmixEnabledChanged(bool checked)
3906 m_settings->forceStereoDownmix(checked);
3910 * Maximum number of instances changed
3912 void MainWindow::updateMaximumInstances(int value)
3914 ui->labelMaxInstances->setText(tr("%n Instance(s)", "", value));
3915 m_settings->maximumInstances(ui->checkBoxAutoDetectInstances->isChecked() ? NULL : value);
3919 * Auto-detect number of instances
3921 void MainWindow::autoDetectInstancesChanged(bool checked)
3923 m_settings->maximumInstances(checked ? NULL : ui->sliderMaxInstances->value());
3927 * Browse for custom TEMP folder button clicked
3929 void MainWindow::browseCustomTempFolderButtonClicked(void)
3931 QString newTempFolder;
3933 if(MUtils::GUI::themes_enabled())
3935 newTempFolder = QFileDialog::getExistingDirectory(this, QString(), m_settings->customTempPath());
3937 else
3939 QFileDialog dialog(this);
3940 dialog.setFileMode(QFileDialog::DirectoryOnly);
3941 dialog.setDirectory(m_settings->customTempPath());
3942 if(dialog.exec())
3944 newTempFolder = dialog.selectedFiles().first();
3948 if(!newTempFolder.isEmpty())
3950 QFile writeTest(QString("%1/~%2.tmp").arg(newTempFolder, MUtils::rand_str()));
3951 if(writeTest.open(QIODevice::ReadWrite))
3953 writeTest.remove();
3954 ui->lineEditCustomTempFolder->setText(QDir::toNativeSeparators(newTempFolder));
3956 else
3958 QMessageBox::warning(this, tr("Access Denied"), tr("Cannot write to the selected directory. Please choose another directory!"));
3964 * Custom TEMP folder changed
3966 void MainWindow::customTempFolderChanged(const QString &text)
3968 m_settings->customTempPath(QDir::fromNativeSeparators(text));
3972 * Use custom TEMP folder option changed
3974 void MainWindow::useCustomTempFolderChanged(bool checked)
3976 m_settings->customTempPathEnabled(!checked);
3980 * Help for custom parameters was requested
3982 void MainWindow::customParamsHelpRequested(QWidget *obj, QEvent *event)
3984 if(event->type() != QEvent::MouseButtonRelease)
3986 return;
3989 if(QMouseEvent *mouseEvent = dynamic_cast<QMouseEvent*>(event))
3991 QPoint pos = mouseEvent->pos();
3992 if(!(pos.x() <= obj->width() && pos.y() <= obj->height() && pos.x() >= 0 && pos.y() >= 0 && mouseEvent->button() != Qt::MidButton))
3994 return;
3998 if(obj == ui->helpCustomParamLAME) showCustomParamsHelpScreen("lame.exe", "--longhelp");
3999 else if(obj == ui->helpCustomParamOggEnc) showCustomParamsHelpScreen("oggenc2.exe", "--help");
4000 else if(obj == ui->helpCustomParamNeroAAC)
4002 switch(EncoderRegistry::getAacEncoder())
4004 case SettingsModel::AAC_ENCODER_QAAC: showCustomParamsHelpScreen("qaac.exe", "--help"); break;
4005 case SettingsModel::AAC_ENCODER_FHG : showCustomParamsHelpScreen("fhgaacenc.exe", ""); break;
4006 case SettingsModel::AAC_ENCODER_NERO: showCustomParamsHelpScreen("neroAacEnc.exe", "-help"); break;
4007 default: MUtils::Sound::beep(MUtils::Sound::BEEP_ERR); break;
4010 else if(obj == ui->helpCustomParamFLAC) showCustomParamsHelpScreen("flac.exe", "--help");
4011 else if(obj == ui->helpCustomParamAften) showCustomParamsHelpScreen("aften.exe", "-h");
4012 else if(obj == ui->helpCustomParamOpus) showCustomParamsHelpScreen("opusenc.exe", "--help");
4013 else MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
4017 * Show help for custom parameters
4019 void MainWindow::showCustomParamsHelpScreen(const QString &toolName, const QString &command)
4021 const QString binary = lamexp_tools_lookup(toolName);
4022 if(binary.isEmpty())
4024 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
4025 qWarning("customParamsHelpRequested: Binary could not be found!");
4026 return;
4029 QProcess process;
4030 MUtils::init_process(process, QFileInfo(binary).absolutePath());
4032 process.start(binary, command.isEmpty() ? QStringList() : QStringList() << command);
4034 qApp->setOverrideCursor(QCursor(Qt::WaitCursor));
4036 if(process.waitForStarted(15000))
4038 qApp->processEvents();
4039 process.waitForFinished(15000);
4042 if(process.state() != QProcess::NotRunning)
4044 process.kill();
4045 process.waitForFinished(-1);
4048 qApp->restoreOverrideCursor();
4049 QStringList output; bool spaceFlag = true;
4051 while(process.canReadLine())
4053 QString temp = QString::fromUtf8(process.readLine());
4054 TRIM_STRING_RIGHT(temp);
4055 if(temp.isEmpty())
4057 if(!spaceFlag) { output << temp; spaceFlag = true; }
4059 else
4061 output << temp; spaceFlag = false;
4065 if(output.count() < 1)
4067 qWarning("Empty output, cannot show help screen!");
4068 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
4071 LogViewDialog *dialog = new LogViewDialog(this);
4072 TEMP_HIDE_DROPBOX( dialog->exec(output); );
4073 MUTILS_DELETE(dialog);
4076 void MainWindow::overwriteModeChanged(int id)
4078 if((id == SettingsModel::Overwrite_Replaces) && (m_settings->overwriteMode() != SettingsModel::Overwrite_Replaces))
4080 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)
4082 ui->radioButtonOverwriteModeKeepBoth->setChecked(m_settings->overwriteMode() == SettingsModel::Overwrite_KeepBoth);
4083 ui->radioButtonOverwriteModeSkipFile->setChecked(m_settings->overwriteMode() == SettingsModel::Overwrite_SkipFile);
4084 return;
4088 m_settings->overwriteMode(id);
4092 * Reset all advanced options to their defaults
4094 void MainWindow::resetAdvancedOptionsButtonClicked(void)
4096 PLAY_SOUND_OPTIONAL("blast", true);
4098 ui->sliderLameAlgoQuality->setValue(m_settings->lameAlgoQualityDefault());
4099 ui->spinBoxBitrateManagementMin->setValue(m_settings->bitrateManagementMinRateDefault());
4100 ui->spinBoxBitrateManagementMax->setValue(m_settings->bitrateManagementMaxRateDefault());
4101 ui->spinBoxNormalizationFilter->setValue(static_cast<double>(m_settings->normalizationFilterMaxVolumeDefault()) / 100.0);
4102 ui->spinBoxToneAdjustBass->setValue(static_cast<double>(m_settings->toneAdjustBassDefault()) / 100.0);
4103 ui->spinBoxToneAdjustTreble->setValue(static_cast<double>(m_settings->toneAdjustTrebleDefault()) / 100.0);
4104 ui->spinBoxAftenSearchSize->setValue(m_settings->aftenExponentSearchSizeDefault());
4105 ui->spinBoxOpusComplexity->setValue(m_settings->opusComplexityDefault());
4106 ui->comboBoxMP3ChannelMode->setCurrentIndex(m_settings->lameChannelModeDefault());
4107 ui->comboBoxSamplingRate->setCurrentIndex(m_settings->samplingRateDefault());
4108 ui->comboBoxAACProfile->setCurrentIndex(m_settings->aacEncProfileDefault());
4109 ui->comboBoxAftenCodingMode->setCurrentIndex(m_settings->aftenAudioCodingModeDefault());
4110 ui->comboBoxAftenDRCMode->setCurrentIndex(m_settings->aftenDynamicRangeCompressionDefault());
4111 ui->comboBoxNormalizationMode->setCurrentIndex(m_settings->normalizationFilterEQModeDefault());
4112 ui->comboBoxOpusFramesize->setCurrentIndex(m_settings->opusFramesizeDefault());
4114 SET_CHECKBOX_STATE(ui->checkBoxBitrateManagement, m_settings->bitrateManagementEnabledDefault());
4115 SET_CHECKBOX_STATE(ui->checkBoxNeroAAC2PassMode, m_settings->neroAACEnable2PassDefault());
4116 SET_CHECKBOX_STATE(ui->checkBoxNormalizationFilter, m_settings->normalizationFilterEnabledDefault());
4117 SET_CHECKBOX_STATE(ui->checkBoxAutoDetectInstances, (m_settings->maximumInstancesDefault() < 1));
4118 SET_CHECKBOX_STATE(ui->checkBoxUseSystemTempFolder, !m_settings->customTempPathEnabledDefault());
4119 SET_CHECKBOX_STATE(ui->checkBoxAftenFastAllocation, m_settings->aftenFastBitAllocationDefault());
4120 SET_CHECKBOX_STATE(ui->checkBoxRenameOutput, m_settings->renameOutputFilesEnabledDefault());
4121 SET_CHECKBOX_STATE(ui->checkBoxForceStereoDownmix, m_settings->forceStereoDownmixDefault());
4122 SET_CHECKBOX_STATE(ui->checkBoxOpusDisableResample, m_settings->opusDisableResampleDefault());
4124 ui->lineEditCustomParamLAME ->setText(m_settings->customParametersLAMEDefault());
4125 ui->lineEditCustomParamOggEnc ->setText(m_settings->customParametersOggEncDefault());
4126 ui->lineEditCustomParamNeroAAC->setText(m_settings->customParametersAacEncDefault());
4127 ui->lineEditCustomParamFLAC ->setText(m_settings->customParametersFLACDefault());
4128 ui->lineEditCustomParamOpus ->setText(m_settings->customParametersOpusEncDefault());
4129 ui->lineEditCustomTempFolder ->setText(QDir::toNativeSeparators(m_settings->customTempPathDefault()));
4130 ui->lineEditRenamePattern ->setText(m_settings->renameOutputFilesPatternDefault());
4132 if(m_settings->overwriteModeDefault() == SettingsModel::Overwrite_KeepBoth) ui->radioButtonOverwriteModeKeepBoth->click();
4133 if(m_settings->overwriteModeDefault() == SettingsModel::Overwrite_SkipFile) ui->radioButtonOverwriteModeSkipFile->click();
4134 if(m_settings->overwriteModeDefault() == SettingsModel::Overwrite_Replaces) ui->radioButtonOverwriteModeReplaces->click();
4136 customParamsChanged();
4137 ui->scrollArea->verticalScrollBar()->setValue(0);
4140 // =========================================================
4141 // Multi-instance handling slots
4142 // =========================================================
4145 * Other instance detected
4147 void MainWindow::notifyOtherInstance(void)
4149 if(!(BANNER_VISIBLE))
4151 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);
4152 msgBox.exec();
4157 * Add file from another instance
4159 void MainWindow::addFileDelayed(const QString &filePath, bool tryASAP)
4161 if(tryASAP && !m_delayedFileTimer->isActive())
4163 qDebug("Received file: %s", MUTILS_UTF8(filePath));
4164 m_delayedFileList->append(filePath);
4165 QTimer::singleShot(0, this, SLOT(handleDelayedFiles()));
4168 m_delayedFileTimer->stop();
4169 qDebug("Received file: %s", MUTILS_UTF8(filePath));
4170 m_delayedFileList->append(filePath);
4171 m_delayedFileTimer->start(5000);
4175 * Add files from another instance
4177 void MainWindow::addFilesDelayed(const QStringList &filePaths, bool tryASAP)
4179 if(tryASAP && (!m_delayedFileTimer->isActive()))
4181 qDebug("Received %d file(s).", filePaths.count());
4182 m_delayedFileList->append(filePaths);
4183 QTimer::singleShot(0, this, SLOT(handleDelayedFiles()));
4185 else
4187 m_delayedFileTimer->stop();
4188 qDebug("Received %d file(s).", filePaths.count());
4189 m_delayedFileList->append(filePaths);
4190 m_delayedFileTimer->start(5000);
4195 * Add folder from another instance
4197 void MainWindow::addFolderDelayed(const QString &folderPath, bool recursive)
4199 if(!(BANNER_VISIBLE))
4201 addFolder(folderPath, recursive, true);
4205 // =========================================================
4206 // Misc slots
4207 // =========================================================
4210 * Restore the override cursor
4212 void MainWindow::restoreCursor(void)
4214 QApplication::restoreOverrideCursor();