1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2014 LoRd_MuldeR <MuldeR2@GMX.de>
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; either version 2 of the License, or
8 // (at your option) any later version, but always including the *additional*
9 // restrictions defined in the "License.txt" file.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License along
17 // with this program; if not, write to the Free Software Foundation, Inc.,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 // http://www.gnu.org/licenses/gpl-2.0.txt
21 ///////////////////////////////////////////////////////////////////////////////
23 #include "Dialog_MainWindow.h"
26 #include "UIC_MainWindow.h"
30 #include "Dialog_WorkingBanner.h"
31 #include "Dialog_MetaInfo.h"
32 #include "Dialog_About.h"
33 #include "Dialog_Update.h"
34 #include "Dialog_DropBox.h"
35 #include "Dialog_CueImport.h"
36 #include "Dialog_LogView.h"
37 #include "Thread_FileAnalyzer.h"
38 #include "Thread_MessageHandler.h"
39 #include "Model_MetaInfo.h"
40 #include "Model_Settings.h"
41 #include "Model_FileList.h"
42 #include "Model_FileSystem.h"
43 #include "Registry_Encoder.h"
44 #include "Registry_Decoder.h"
45 #include "Encoder_Abstract.h"
46 #include "ShellIntegration.h"
47 #include "CustomEventFilter.h"
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>
59 #include <QMessageBox>
61 #include <QDesktopWidget>
63 #include <QFileDialog>
64 #include <QInputDialog>
65 #include <QFileSystemModel>
66 #include <QDesktopServices>
68 #include <QPlastiqueStyle>
69 #include <QCleanlooksStyle>
70 #include <QWindowsVistaStyle>
71 #include <QWindowsStyle>
73 #include <QDragEnterEvent>
77 #include <QProcessEnvironment>
78 #include <QCryptographicHash>
79 #include <QTranslator>
83 ////////////////////////////////////////////////////////////
85 ////////////////////////////////////////////////////////////
87 #define BANNER_VISIBLE ((m_banner != NULL) && m_banner->isVisible())
89 #define INIT_BANNER() do \
91 if(m_banner == NULL) \
93 m_banner = new WorkingBanner(this); \
98 #define SHOW_BANNER(TXT) do \
101 m_banner->show((TXT)); \
105 #define SHOW_BANNER_ARG(TXT, ARG) do \
108 m_banner->show((TXT), (ARG)); \
113 #define SHOW_BANNER_CONDITIONALLY(FLAG, TEST, TXT) do \
115 if((!(FLAG)) && ((TEST))) \
118 m_banner->show((TXT)); \
124 #define ABORT_IF_BUSY do \
126 if(BANNER_VISIBLE || m_delayedFileTimer->isActive() || (QApplication::activeModalWidget() != NULL)) \
128 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN); \
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); \
143 #define SET_FONT_BOLD(WIDGET,BOLD) do \
145 QFont _font = WIDGET->font(); \
146 _font.setBold(BOLD); \
147 WIDGET->setFont(_font); \
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(); \
160 #define SET_MODEL(VIEW, MODEL) do \
162 QItemSelectionModel *_tmp = (VIEW)->selectionModel(); \
163 (VIEW)->setModel(MODEL); \
164 MUTILS_DELETE(_tmp); \
168 #define SET_CHECKBOX_STATE(CHCKBX, STATE) do \
170 if((CHCKBX)->isChecked() != (STATE)) \
174 if((CHCKBX)->isChecked() != (STATE)) \
176 qWarning("Warning: Failed to set checkbox " #CHCKBX " state!"); \
181 #define TRIM_STRING_RIGHT(STR) do \
183 while((STR.length() > 0) && STR[STR.length()-1].isSpace()) STR.chop(1); \
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()); \
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); } \
203 #define PLAY_SOUND_OPTIONAL(NAME, ASYNC) do \
205 if(m_settings->soundsEnabled()) MUtils::Sound::play_sound((NAME), (ASYNC)); \
209 #define SHOW_CORNER_WIDGET(FLAG) do \
211 if(QWidget *cornerWidget = ui->menubar->cornerWidget()) \
213 cornerWidget->setVisible((FLAG)); \
218 #define LINK(URL) QString("<a href=\"%1\">%2</a>").arg(URL).arg(QString(URL).replace("-", "−"))
219 #define FSLINK(PATH) QString("<a href=\"file:///%1\">%2</a>").arg(PATH).arg(QString(PATH).replace("-", "−"))
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 ////////////////////////////////////////////////////////////
228 ////////////////////////////////////////////////////////////
230 MainWindow::MainWindow(MUtils::IPCChannel *const ipcChannel, FileListModel *const fileListModel, AudioFileModel_MetaInfo *const metaInfo, SettingsModel *const settingsModel, QWidget *const parent)
233 ui(new Ui::MainWindow),
234 m_fileListModel(fileListModel),
235 m_metaData(metaInfo),
236 m_settings(settingsModel),
237 m_fileSystemModel(NULL),
240 m_firstTimeShown(true),
241 m_outputFolderViewCentering(false),
242 m_outputFolderViewInitCounter(0)
244 //Init the dialog, from the .ui file
246 setWindowFlags(windowFlags() ^ Qt::WindowMaximizeButtonHint);
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()));
260 ui->tabWidget->setCurrentIndex(0);
261 connect(ui->tabWidget, SIGNAL(currentChanged(int)), this, SLOT(tabPageChanged(int)));
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());
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);
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()));
699 initializeTranslation();
701 //Re-translate (make sure we translate once)
702 QEvent languageChangeEvent(QEvent::LanguageChange);
703 changeEvent(&languageChangeEvent);
706 m_droppedFileList = new QList<QUrl>();
707 this->setAcceptDrops(true);
710 ////////////////////////////////////////////////////////////
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();
728 SET_MODEL(ui->sourceFileView, NULL);
729 SET_MODEL(ui->outputFolderView, NULL);
730 SET_MODEL(ui->metaDataView, NULL);
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
760 ////////////////////////////////////////////////////////////
762 ////////////////////////////////////////////////////////////
765 * Add file to source list
767 void MainWindow::addFiles(const QStringList &files)
774 WITH_BLOCKED_SIGNALS(ui->tabWidget, setCurrentIndex, 0);
775 tabPageChanged(ui->tabWidget->currentIndex(), true);
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);
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);
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);
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);
861 folderInfoList.append(currentDir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks));
862 QApplication::processEvents();
867 QApplication::processEvents();
869 if(!fileList.isEmpty())
873 addFilesDelayed(fileList);
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()));
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!");
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()));
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 ////////////////////////////////////////////////////////////
1025 ////////////////////////////////////////////////////////////
1028 * Window is about to be shown
1030 void MainWindow::showEvent(QShowEvent *event)
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()));
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)
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
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\"> <b style=\"color:darkred\">%1</b> </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"));
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);
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()));
1226 if(e->modifiers().testFlag(Qt::ControlModifier) && (e->key() == Qt::Key_F5))
1228 initializeTranslation();
1229 MUtils::Sound::beep(MUtils::Sound::BEEP_NFO);
1233 if(e->key() == Qt::Key_F5)
1235 if(ui->outputFolderView->isVisible())
1237 QTimer::singleShot(0, this, SLOT(refreshFolderContextActionTriggered()));
1242 QMainWindow::keyPressEvent(e);
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)
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();
1271 case MUtils::GUI::USER_EVENT_ENDSESSION:
1272 qWarning("System is shutting down, main window will close now...");
1277 QApplication::processEvents(QEventLoop::WaitForMoreEvents & QEventLoop::ExcludeUserInputEvents);
1280 m_fileListModel->clearFiles();
1282 case QEvent::MouseButtonPress:
1283 if(ui->outputFolderEdit->isVisible())
1285 QTimer::singleShot(0, this, SLOT(outputFolderEditFinished()));
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()));
1303 ////////////////////////////////////////////////////////////
1305 ////////////////////////////////////////////////////////////
1307 // =========================================================
1308 // Show window slots
1309 // =========================================================
1314 void MainWindow::windowShown(void)
1316 const QStringList &arguments = MUtils::OS::arguments(); //QApplication::arguments();
1318 //Force resize event
1322 bool firstRun = false;
1323 for(int i = 0; i < arguments.count(); i++)
1325 /*QMessageBox::information(this, QString::number(i), arguments[i]);*/
1326 if(!arguments[i].compare("--first-run", Qt::CaseInsensitive)) firstRun = true;
1330 if((m_settings->licenseAccepted() <= 0) || firstRun)
1332 int iAccepted = m_settings->licenseAccepted();
1334 if((iAccepted == 0) || firstRun)
1336 AboutDialog *about = new AboutDialog(m_settings, this, true);
1337 iAccepted = about->exec();
1338 if(iAccepted <= 0) iAccepted = -2;
1339 MUTILS_DELETE(about);
1344 m_settings->licenseAccepted(++iAccepted);
1345 m_settings->syncNow();
1346 QApplication::processEvents();
1347 MUtils::Sound::play_sound("whammy", false);
1348 QMessageBox::critical(this, tr("License Declined"), tr("You have declined the license. Consequently the application will exit now!"), tr("Goodbye!"));
1349 QFileInfo uninstallerInfo = QFileInfo(QString("%1/Uninstall.exe").arg(QApplication::applicationDirPath()));
1350 if(uninstallerInfo.exists())
1352 QString uninstallerDir = uninstallerInfo.canonicalPath();
1353 QString uninstallerPath = uninstallerInfo.canonicalFilePath();
1354 for(int i = 0; i < 3; i++)
1356 if(MUtils::OS::shell_open(this, QDir::toNativeSeparators(uninstallerPath), "/Force", QDir::toNativeSeparators(uninstallerDir))) break;
1359 QApplication::quit();
1363 MUtils::Sound::play_sound("woohoo", false);
1364 m_settings->licenseAccepted(1);
1365 m_settings->syncNow();
1366 if(lamexp_version_demo()) showAnnounceBox();
1369 //Check for expiration
1370 if(lamexp_version_demo())
1372 if(MUtils::OS::current_date() >= lamexp_version_expires())
1374 qWarning("Binary has expired !!!");
1375 MUtils::Sound::play_sound("whammy", false);
1376 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)
1380 QApplication::quit();
1385 //Slow startup indicator
1386 if(m_settings->slowStartup() && m_settings->antivirNotificationsEnabled())
1389 message += NOBR(tr("It seems that a bogus anti-virus software is slowing down the startup of LameXP.")).append("<br>");
1390 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>");
1391 if(QMessageBox::warning(this, tr("Slow Startup"), message, tr("Discard"), tr("Don't Show Again")) == 1)
1393 m_settings->antivirNotificationsEnabled(false);
1394 ui->actionDisableSlowStartupNotifications->setChecked(!m_settings->antivirNotificationsEnabled());
1399 if(MUtils::OS::current_date() >= MUtils::Version::app_build_date().addYears(1))
1401 qWarning("Binary is more than a year old, time to update!");
1402 SHOW_CORNER_WIDGET(true);
1403 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"));
1407 if(checkForUpdates())
1409 QApplication::quit();
1414 QApplication::quit();
1417 QEventLoop loop; QTimer::singleShot(7000, &loop, SLOT(quit()));
1418 MUtils::Sound::play_sound("waiting", true);
1419 SHOW_BANNER_ARG(tr("Skipping update check this time, please be patient..."), &loop);
1425 QDate lastUpdateCheck = QDate::fromString(m_settings->autoUpdateLastCheck(), Qt::ISODate);
1426 if((!firstRun) && ((!lastUpdateCheck.isValid()) || (MUtils::OS::current_date() >= lastUpdateCheck.addDays(14))))
1428 SHOW_CORNER_WIDGET(true);
1429 if(m_settings->autoUpdateEnabled())
1431 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)
1433 if(checkForUpdates())
1435 QApplication::quit();
1443 //Check for AAC support
1444 const int aacEncoder = EncoderRegistry::getAacEncoder();
1445 if(aacEncoder == SettingsModel::AAC_ENCODER_NERO)
1447 if(m_settings->neroAacNotificationsEnabled())
1449 if(lamexp_tools_version("neroAacEnc.exe") < lamexp_toolver_neroaac())
1451 QString messageText;
1452 messageText += NOBR(tr("LameXP detected that your version of the Nero AAC encoder is outdated!")).append("<br>");
1453 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>");
1454 messageText += NOBR(tr("You can download the latest version of the Nero AAC encoder from the Nero website at:")).append("<br>");
1455 messageText += "<nobr><tt>" + LINK(AboutDialog::neroAacUrl) + "</tt></nobr><br><br>";
1456 messageText += NOBR(tr("(Hint: Please ignore the name of the downloaded ZIP file and check the included 'changelog.txt' instead!)")).append("<br>");
1457 QMessageBox::information(this, tr("AAC Encoder Outdated"), messageText);
1463 if(m_settings->neroAacNotificationsEnabled() && (aacEncoder <= SettingsModel::AAC_ENCODER_NONE))
1465 QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
1466 if(appPath.isEmpty()) appPath = QCoreApplication::applicationDirPath();
1467 QString messageText;
1468 messageText += NOBR(tr("The Nero AAC encoder could not be found. AAC encoding support will be disabled.")).append("<br>");
1469 messageText += NOBR(tr("Please put 'neroAacEnc.exe', 'neroAacDec.exe' and 'neroAacTag.exe' into the LameXP directory!")).append("<br><br>");
1470 messageText += NOBR(tr("Your LameXP directory is located here:")).append("<br>");
1471 messageText += QString("<nobr><tt>%1</tt></nobr><br><br>").arg(FSLINK(QDir::toNativeSeparators(appPath)));
1472 messageText += NOBR(tr("You can download the Nero AAC encoder for free from the official Nero website at:")).append("<br>");
1473 messageText += "<nobr><tt>" + LINK(AboutDialog::neroAacUrl) + "</tt></nobr><br>";
1474 if(QMessageBox::information(this, tr("AAC Support Disabled"), messageText, tr("Discard"), tr("Don't Show Again")) == 1)
1476 m_settings->neroAacNotificationsEnabled(false);
1477 ui->actionDisableNeroAacNotifications->setChecked(!m_settings->neroAacNotificationsEnabled());
1482 //Add files from the command-line
1483 for(int i = 0; i < arguments.count() - 1; i++)
1485 QStringList addedFiles;
1486 if(!arguments[i].compare("--add", Qt::CaseInsensitive))
1488 QFileInfo currentFile(arguments[++i].trimmed());
1489 qDebug("Adding file from CLI: %s", MUTILS_UTF8(currentFile.absoluteFilePath()));
1490 addedFiles.append(currentFile.absoluteFilePath());
1492 if(!addedFiles.isEmpty())
1494 addFilesDelayed(addedFiles);
1498 //Add folders from the command-line
1499 for(int i = 0; i < arguments.count() - 1; i++)
1501 if(!arguments[i].compare("--add-folder", Qt::CaseInsensitive))
1503 QFileInfo currentFile(arguments[++i].trimmed());
1504 qDebug("Adding folder from CLI: %s", MUTILS_UTF8(currentFile.absoluteFilePath()));
1505 addFolder(currentFile.absoluteFilePath(), false, true);
1507 if(!arguments[i].compare("--add-recursive", Qt::CaseInsensitive))
1509 QFileInfo currentFile(arguments[++i].trimmed());
1510 qDebug("Adding folder recursively from CLI: %s", MUTILS_UTF8(currentFile.absoluteFilePath()));
1511 addFolder(currentFile.absoluteFilePath(), true, true);
1515 //Enable shell integration
1516 if(m_settings->shellIntegrationEnabled())
1518 ShellIntegration::install();
1521 //Make DropBox visible
1522 if(m_settings->dropBoxWidgetEnabled())
1524 m_dropBox->setVisible(true);
1531 void MainWindow::showAnnounceBox(void)
1533 const unsigned int timeout = 8U;
1535 const QString announceText = QString("%1<br><br>%2<br><nobr><tt>%3</tt></nobr><br>").arg
1537 NOBR("We are still looking for LameXP translators!"),
1538 NOBR("If you are willing to translate LameXP to your language or to complete an existing translation, please refer to:"),
1539 LINK("http://lamexp.sourceforge.net/doc/Translate.html")
1542 QMessageBox *announceBox = new QMessageBox(QMessageBox::Warning, "We want you!", announceText, QMessageBox::NoButton, this);
1543 announceBox->setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
1544 announceBox->setIconPixmap(QIcon(":/images/Announcement.png").pixmap(64,79));
1546 QTimer *timers[timeout+1];
1547 QPushButton *buttons[timeout+1];
1549 for(unsigned int i = 0; i <= timeout; i++)
1551 QString text = (i > 0) ? QString("%1 (%2)").arg(tr("Discard"), QString::number(i)) : tr("Discard");
1552 buttons[i] = announceBox->addButton(text, (i > 0) ? QMessageBox::NoRole : QMessageBox::AcceptRole);
1555 for(unsigned int i = 0; i <= timeout; i++)
1557 buttons[i]->setEnabled(i == 0);
1558 buttons[i]->setVisible(i == timeout);
1561 for(unsigned int i = 0; i < timeout; i++)
1563 timers[i] = new QTimer(this);
1564 timers[i]->setSingleShot(true);
1565 timers[i]->setInterval(1000);
1566 connect(timers[i], SIGNAL(timeout()), buttons[i+1], SLOT(hide()));
1567 connect(timers[i], SIGNAL(timeout()), buttons[i], SLOT(show()));
1570 connect(timers[i], SIGNAL(timeout()), timers[i-1], SLOT(start()));
1574 timers[timeout-1]->start();
1575 announceBox->exec();
1577 for(unsigned int i = 0; i < timeout; i++)
1580 MUTILS_DELETE(timers[i]);
1583 MUTILS_DELETE(announceBox);
1586 // =========================================================
1587 // Main button solots
1588 // =========================================================
1593 void MainWindow::encodeButtonClicked(void)
1595 static const unsigned __int64 oneGigabyte = 1073741824ui64;
1596 static const unsigned __int64 minimumFreeDiskspaceMultiplier = 2ui64;
1597 static const char *writeTestBuffer = "LAMEXP_WRITE_TEST";
1601 if(m_fileListModel->rowCount() < 1)
1603 QMessageBox::warning(this, tr("LameXP"), NOBR(tr("You must add at least one file to the list before proceeding!")));
1604 ui->tabWidget->setCurrentIndex(0);
1608 QString tempFolder = m_settings->customTempPathEnabled() ? m_settings->customTempPath() : MUtils::temp_folder();
1609 if(!QFileInfo(tempFolder).exists() || !QFileInfo(tempFolder).isDir())
1611 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)
1613 SET_CHECKBOX_STATE(ui->checkBoxUseSystemTempFolder, m_settings->customTempPathEnabledDefault());
1618 quint64 currentFreeDiskspace = 0;
1619 if(MUtils::OS::free_diskspace(tempFolder, currentFreeDiskspace))
1621 if(currentFreeDiskspace < (oneGigabyte * minimumFreeDiskspaceMultiplier))
1623 QStringList tempFolderParts = tempFolder.split("/", QString::SkipEmptyParts, Qt::CaseInsensitive);
1624 tempFolderParts.takeLast();
1625 PLAY_SOUND_OPTIONAL("whammy", false);
1626 QString lowDiskspaceMsg = QString("%1<br>%2<br><br>%3<br>%4<br>").arg
1628 NOBR(tr("There are less than %1 GB of free diskspace available on your system's TEMP folder.").arg(QString::number(minimumFreeDiskspaceMultiplier))),
1629 NOBR(tr("It is highly recommend to free up more diskspace before proceeding with the encode!")),
1630 NOBR(tr("Your TEMP folder is located at:")),
1631 QString("<nobr><tt>%1</tt></nobr>").arg(FSLINK(tempFolderParts.join("\\")))
1633 switch(QMessageBox::warning(this, tr("Low Diskspace Warning"), lowDiskspaceMsg, tr("Abort Encoding Process"), tr("Clean Disk Now"), tr("Ignore")))
1636 QProcess::startDetached(QString("%1/cleanmgr.exe").arg(MUtils::OS::known_folder(MUtils::OS::FOLDER_SYSTEMFOLDER)), QStringList() << "/D" << tempFolderParts.first());
1641 QMessageBox::warning(this, tr("Low Diskspace"), NOBR(tr("You are proceeding with low diskspace. Problems might occur!")));
1647 switch(m_settings->compressionEncoder())
1649 case SettingsModel::MP3Encoder:
1650 case SettingsModel::VorbisEncoder:
1651 case SettingsModel::AACEncoder:
1652 case SettingsModel::AC3Encoder:
1653 case SettingsModel::FLACEncoder:
1654 case SettingsModel::OpusEncoder:
1655 case SettingsModel::DCAEncoder:
1656 case SettingsModel::MACEncoder:
1657 case SettingsModel::PCMEncoder:
1660 QMessageBox::warning(this, tr("LameXP"), tr("Sorry, an unsupported encoder has been chosen!"));
1661 ui->tabWidget->setCurrentIndex(3);
1665 if(!m_settings->outputToSourceDir())
1667 QFile writeTest(QString("%1/~%2.txt").arg(m_settings->outputDir(), MUtils::rand_str()));
1668 if(!(writeTest.open(QIODevice::ReadWrite) && (writeTest.write(writeTestBuffer) == strlen(writeTestBuffer))))
1670 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!")));
1671 ui->tabWidget->setCurrentIndex(1);
1688 void MainWindow::aboutButtonClicked(void)
1694 AboutDialog *aboutBox = new AboutDialog(m_settings, this);
1696 MUTILS_DELETE(aboutBox);
1703 void MainWindow::closeButtonClicked(void)
1709 // =========================================================
1711 // =========================================================
1716 void MainWindow::tabPageChanged(int idx, const bool silent)
1720 //Update "view" menu
1721 QList<QAction*> actions = m_tabActionGroup->actions();
1722 for(int i = 0; i < actions.count(); i++)
1725 int actionIndex = actions.at(i)->data().toInt(&ok);
1726 if(ok && actionIndex == idx)
1728 actions.at(i)->setChecked(true);
1735 PLAY_SOUND_OPTIONAL("tick", true);
1738 int initialWidth = this->width();
1739 int maximumWidth = QApplication::desktop()->availableGeometry().width();
1741 //Make sure all tab headers are fully visible
1742 if(this->isVisible())
1744 int delta = ui->tabWidget->sizeHint().width() - ui->tabWidget->width();
1747 this->resize(qMin(this->width() + delta, maximumWidth), this->height());
1751 //Tab specific operations
1752 if(idx == ui->tabWidget->indexOf(ui->tabOptions) && ui->scrollArea->widget() && this->isVisible())
1754 ui->scrollArea->widget()->updateGeometry();
1755 ui->scrollArea->viewport()->updateGeometry();
1756 qApp->processEvents();
1757 int delta = ui->scrollArea->widget()->width() - ui->scrollArea->viewport()->width();
1760 this->resize(qMin(this->width() + delta, maximumWidth), this->height());
1763 else if(idx == ui->tabWidget->indexOf(ui->tabSourceFiles))
1765 m_dropNoteLabel->setGeometry(0, 0, ui->sourceFileView->width(), ui->sourceFileView->height());
1767 else if(idx == ui->tabWidget->indexOf(ui->tabOutputDir))
1769 if(!m_fileSystemModel)
1771 QTimer::singleShot(125, this, SLOT(initOutputFolderModel()));
1775 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
1779 //Center window around previous position
1780 if(initialWidth < this->width())
1782 QPoint prevPos = this->pos();
1783 int delta = (this->width() - initialWidth) >> 2;
1784 move(prevPos.x() - delta, prevPos.y());
1789 * Tab action triggered
1791 void MainWindow::tabActionActivated(QAction *action)
1793 if(action && action->data().isValid())
1796 int index = action->data().toInt(&ok);
1799 ui->tabWidget->setCurrentIndex(index);
1804 // =========================================================
1806 // =========================================================
1809 * Handle corner widget Event
1811 void MainWindow::cornerWidgetEventOccurred(QWidget *sender, QEvent *event)
1813 if(event->type() == QEvent::MouseButtonPress)
1815 QTimer::singleShot(0, this, SLOT(checkUpdatesActionActivated()));
1819 // =========================================================
1821 // =========================================================
1824 * Style action triggered
1826 void MainWindow::styleActionActivated(QAction *action)
1828 //Change style setting
1829 if(action && action->data().isValid())
1832 int actionIndex = action->data().toInt(&ok);
1835 m_settings->interfaceStyle(actionIndex);
1839 //Set up the new style
1840 switch(m_settings->interfaceStyle())
1843 if(ui->actionStyleCleanlooks->isEnabled())
1845 ui->actionStyleCleanlooks->setChecked(true);
1846 QApplication::setStyle(new QCleanlooksStyle());
1850 if(ui->actionStyleWindowsVista->isEnabled())
1852 ui->actionStyleWindowsVista->setChecked(true);
1853 QApplication::setStyle(new QWindowsVistaStyle());
1857 if(ui->actionStyleWindowsXP->isEnabled())
1859 ui->actionStyleWindowsXP->setChecked(true);
1860 QApplication::setStyle(new QWindowsXPStyle());
1864 if(ui->actionStyleWindowsClassic->isEnabled())
1866 ui->actionStyleWindowsClassic->setChecked(true);
1867 QApplication::setStyle(new QWindowsStyle());
1871 ui->actionStylePlastique->setChecked(true);
1872 QApplication::setStyle(new QPlastiqueStyle());
1876 //Force re-translate after style change
1877 if(QEvent *e = new QEvent(QEvent::LanguageChange))
1884 const type_info &styleType = typeid(*qApp->style());
1885 const bool bTransparent = ((typeid(QWindowsVistaStyle) == styleType) || (typeid(QWindowsXPStyle) == styleType));
1886 MAKE_TRANSPARENT(ui->scrollArea, bTransparent);
1888 //Also force a re-size event
1889 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
1894 * Language action triggered
1896 void MainWindow::languageActionActivated(QAction *action)
1898 if(action->data().type() == QVariant::String)
1900 QString langId = action->data().toString();
1902 if(MUtils::Translation::install_translator(langId))
1904 action->setChecked(true);
1905 ui->actionLoadTranslationFromFile->setChecked(false);
1906 m_settings->currentLanguage(langId);
1907 m_settings->currentLanguageFile(QString());
1913 * Load language from file action triggered
1915 void MainWindow::languageFromFileActionActivated(bool checked)
1917 QFileDialog dialog(this, tr("Load Translation"));
1918 dialog.setFileMode(QFileDialog::ExistingFile);
1919 dialog.setNameFilter(QString("%1 (*.qm)").arg(tr("Translation Files")));
1923 QStringList selectedFiles = dialog.selectedFiles();
1924 const QString qmFile = QFileInfo(selectedFiles.first()).canonicalFilePath();
1925 if(MUtils::Translation::install_translator_from_file(qmFile))
1927 QList<QAction*> actions = m_languageActionGroup->actions();
1928 while(!actions.isEmpty())
1930 actions.takeFirst()->setChecked(false);
1932 ui->actionLoadTranslationFromFile->setChecked(true);
1933 m_settings->currentLanguageFile(qmFile);
1937 languageActionActivated(m_languageActionGroup->actions().first());
1942 // =========================================================
1944 // =========================================================
1947 * Disable update reminder action
1949 void MainWindow::disableUpdateReminderActionTriggered(bool checked)
1953 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))
1955 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!"))));
1956 m_settings->autoUpdateEnabled(false);
1960 m_settings->autoUpdateEnabled(true);
1965 QMessageBox::information(this, tr("Update Reminder"), NOBR(tr("The update reminder has been re-enabled.")));
1966 m_settings->autoUpdateEnabled(true);
1969 ui->actionDisableUpdateReminder->setChecked(!m_settings->autoUpdateEnabled());
1973 * Disable sound effects action
1975 void MainWindow::disableSoundsActionTriggered(bool checked)
1979 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))
1981 QMessageBox::information(this, tr("Sound Effects"), NOBR(tr("All sound effects have been disabled.")));
1982 m_settings->soundsEnabled(false);
1986 m_settings->soundsEnabled(true);
1991 QMessageBox::information(this, tr("Sound Effects"), NOBR(tr("The sound effects have been re-enabled.")));
1992 m_settings->soundsEnabled(true);
1995 ui->actionDisableSounds->setChecked(!m_settings->soundsEnabled());
1999 * Disable Nero AAC encoder action
2001 void MainWindow::disableNeroAacNotificationsActionTriggered(bool checked)
2005 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))
2007 QMessageBox::information(this, tr("Nero AAC Notifications"), NOBR(tr("All Nero AAC Encoder notifications have been disabled.")));
2008 m_settings->neroAacNotificationsEnabled(false);
2012 m_settings->neroAacNotificationsEnabled(true);
2017 QMessageBox::information(this, tr("Nero AAC Notifications"), NOBR(tr("The Nero AAC Encoder notifications have been re-enabled.")));
2018 m_settings->neroAacNotificationsEnabled(true);
2021 ui->actionDisableNeroAacNotifications->setChecked(!m_settings->neroAacNotificationsEnabled());
2025 * Disable slow startup action
2027 void MainWindow::disableSlowStartupNotificationsActionTriggered(bool checked)
2031 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))
2033 QMessageBox::information(this, tr("Slow Startup Notifications"), NOBR(tr("The slow startup notifications have been disabled.")));
2034 m_settings->antivirNotificationsEnabled(false);
2038 m_settings->antivirNotificationsEnabled(true);
2043 QMessageBox::information(this, tr("Slow Startup Notifications"), NOBR(tr("The slow startup notifications have been re-enabled.")));
2044 m_settings->antivirNotificationsEnabled(true);
2047 ui->actionDisableSlowStartupNotifications->setChecked(!m_settings->antivirNotificationsEnabled());
2051 * Import a Cue Sheet file
2053 void MainWindow::importCueSheetActionTriggered(bool checked)
2062 QString selectedCueFile;
2064 if(MUtils::GUI::themes_enabled())
2066 selectedCueFile = QFileDialog::getOpenFileName(this, tr("Open Cue Sheet"), m_settings->mostRecentInputPath(), QString("%1 (*.cue)").arg(tr("Cue Sheet File")));
2070 QFileDialog dialog(this, tr("Open Cue Sheet"));
2071 dialog.setFileMode(QFileDialog::ExistingFile);
2072 dialog.setNameFilter(QString("%1 (*.cue)").arg(tr("Cue Sheet File")));
2073 dialog.setDirectory(m_settings->mostRecentInputPath());
2076 selectedCueFile = dialog.selectedFiles().first();
2080 if(!selectedCueFile.isEmpty())
2082 m_settings->mostRecentInputPath(QFileInfo(selectedCueFile).canonicalPath());
2083 CueImportDialog *cueImporter = new CueImportDialog(this, m_fileListModel, selectedCueFile, m_settings);
2084 result = cueImporter->exec();
2085 MUTILS_DELETE(cueImporter);
2088 if(result == QDialog::Accepted)
2090 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
2091 ui->sourceFileView->update();
2092 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
2093 ui->sourceFileView->scrollToBottom();
2094 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
2097 if(result != (-1)) break;
2103 * Show the "drop box" widget
2105 void MainWindow::showDropBoxWidgetActionTriggered(bool checked)
2107 m_settings->dropBoxWidgetEnabled(true);
2109 if(!m_dropBox->isVisible())
2112 QTimer::singleShot(2500, m_dropBox, SLOT(showToolTip()));
2115 MUtils::GUI::blink_window(m_dropBox);
2119 * Check for beta (pre-release) updates
2121 void MainWindow::checkForBetaUpdatesActionTriggered(bool checked)
2123 bool checkUpdatesNow = false;
2127 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))
2129 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")))
2131 checkUpdatesNow = true;
2133 m_settings->autoUpdateCheckBeta(true);
2137 m_settings->autoUpdateCheckBeta(false);
2142 QMessageBox::information(this, tr("Beta Updates"), NOBR(tr("LameXP will <i>not</i> check for Beta (pre-release) updates from now on.")));
2143 m_settings->autoUpdateCheckBeta(false);
2146 ui->actionCheckForBetaUpdates->setChecked(m_settings->autoUpdateCheckBeta());
2150 if(checkForUpdates())
2152 QApplication::quit();
2158 * Hibernate computer action
2160 void MainWindow::hibernateComputerActionTriggered(bool checked)
2164 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))
2166 QMessageBox::information(this, tr("Hibernate Computer"), NOBR(tr("LameXP will hibernate the computer on shutdown from now on.")));
2167 m_settings->hibernateComputer(true);
2171 m_settings->hibernateComputer(false);
2176 QMessageBox::information(this, tr("Hibernate Computer"), NOBR(tr("LameXP will <i>not</i> hibernate the computer on shutdown from now on.")));
2177 m_settings->hibernateComputer(false);
2180 ui->actionHibernateComputer->setChecked(m_settings->hibernateComputer());
2184 * Disable shell integration action
2186 void MainWindow::disableShellIntegrationActionTriggered(bool checked)
2190 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))
2192 ShellIntegration::remove();
2193 QMessageBox::information(this, tr("Shell Integration"), NOBR(tr("The LameXP shell integration has been disabled.")));
2194 m_settings->shellIntegrationEnabled(false);
2198 m_settings->shellIntegrationEnabled(true);
2203 ShellIntegration::install();
2204 QMessageBox::information(this, tr("Shell Integration"), NOBR(tr("The LameXP shell integration has been re-enabled.")));
2205 m_settings->shellIntegrationEnabled(true);
2208 ui->actionDisableShellIntegration->setChecked(!m_settings->shellIntegrationEnabled());
2210 if(lamexp_version_portable() && ui->actionDisableShellIntegration->isChecked())
2212 ui->actionDisableShellIntegration->setEnabled(false);
2216 // =========================================================
2218 // =========================================================
2221 * Visit homepage action
2223 void MainWindow::visitHomepageActionActivated(void)
2225 if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
2227 if(action->data().isValid() && (action->data().type() == QVariant::String))
2229 QDesktopServices::openUrl(QUrl(action->data().toString()));
2237 void MainWindow::documentActionActivated(void)
2239 if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
2241 openDocumentLink(action);
2246 * Check for updates action
2248 void MainWindow::checkUpdatesActionActivated(void)
2255 bFlag = checkForUpdates();
2260 QApplication::quit();
2264 // =========================================================
2265 // Source file slots
2266 // =========================================================
2269 * Add file(s) button
2271 void MainWindow::addFilesButtonClicked(void)
2277 if(MUtils::GUI::themes_enabled())
2279 QStringList fileTypeFilters = DecoderRegistry::getSupportedTypes();
2280 QStringList selectedFiles = QFileDialog::getOpenFileNames(this, tr("Add file(s)"), m_settings->mostRecentInputPath(), fileTypeFilters.join(";;"));
2281 if(!selectedFiles.isEmpty())
2283 m_settings->mostRecentInputPath(QFileInfo(selectedFiles.first()).canonicalPath());
2284 addFiles(selectedFiles);
2289 QFileDialog dialog(this, tr("Add file(s)"));
2290 QStringList fileTypeFilters = DecoderRegistry::getSupportedTypes();
2291 dialog.setFileMode(QFileDialog::ExistingFiles);
2292 dialog.setNameFilter(fileTypeFilters.join(";;"));
2293 dialog.setDirectory(m_settings->mostRecentInputPath());
2296 QStringList selectedFiles = dialog.selectedFiles();
2297 if(!selectedFiles.isEmpty())
2299 m_settings->mostRecentInputPath(QFileInfo(selectedFiles.first()).canonicalPath());
2300 addFiles(selectedFiles);
2308 * Open folder action
2310 void MainWindow::openFolderActionActivated(void)
2313 QString selectedFolder;
2315 if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
2319 if(MUtils::GUI::themes_enabled())
2321 selectedFolder = QFileDialog::getExistingDirectory(this, tr("Add Folder"), m_settings->mostRecentInputPath());
2325 QFileDialog dialog(this, tr("Add Folder"));
2326 dialog.setFileMode(QFileDialog::DirectoryOnly);
2327 dialog.setDirectory(m_settings->mostRecentInputPath());
2330 selectedFolder = dialog.selectedFiles().first();
2334 if(!selectedFolder.isEmpty())
2336 m_settings->mostRecentInputPath(QDir(selectedFolder).canonicalPath());
2337 addFolder(selectedFolder, action->data().toBool());
2344 * Remove file button
2346 void MainWindow::removeFileButtonClicked(void)
2348 if(ui->sourceFileView->currentIndex().isValid())
2350 int iRow = ui->sourceFileView->currentIndex().row();
2351 m_fileListModel->removeFile(ui->sourceFileView->currentIndex());
2352 ui->sourceFileView->selectRow(iRow < m_fileListModel->rowCount() ? iRow : m_fileListModel->rowCount()-1);
2357 * Clear files button
2359 void MainWindow::clearFilesButtonClicked(void)
2361 m_fileListModel->clearFiles();
2365 * Move file up button
2367 void MainWindow::fileUpButtonClicked(void)
2369 if(ui->sourceFileView->currentIndex().isValid())
2371 int iRow = ui->sourceFileView->currentIndex().row() - 1;
2372 m_fileListModel->moveFile(ui->sourceFileView->currentIndex(), -1);
2373 ui->sourceFileView->selectRow(iRow >= 0 ? iRow : 0);
2378 * Move file down button
2380 void MainWindow::fileDownButtonClicked(void)
2382 if(ui->sourceFileView->currentIndex().isValid())
2384 int iRow = ui->sourceFileView->currentIndex().row() + 1;
2385 m_fileListModel->moveFile(ui->sourceFileView->currentIndex(), 1);
2386 ui->sourceFileView->selectRow(iRow < m_fileListModel->rowCount() ? iRow : m_fileListModel->rowCount()-1);
2391 * Show details button
2393 void MainWindow::showDetailsButtonClicked(void)
2398 MetaInfoDialog *metaInfoDialog = new MetaInfoDialog(this);
2399 QModelIndex index = ui->sourceFileView->currentIndex();
2401 while(index.isValid())
2405 index = m_fileListModel->index(index.row() + 1, index.column());
2406 ui->sourceFileView->selectRow(index.row());
2410 index = m_fileListModel->index(index.row() - 1, index.column());
2411 ui->sourceFileView->selectRow(index.row());
2414 AudioFileModel &file = (*m_fileListModel)[index];
2417 iResult = metaInfoDialog->exec(file, index.row() > 0, index.row() < m_fileListModel->rowCount() - 1);
2420 //Copy all info to Meta Info tab
2421 if(iResult == INT_MAX)
2423 m_metaInfoModel->assignInfoFrom(file);
2424 ui->tabWidget->setCurrentIndex(ui->tabWidget->indexOf(ui->tabMetaData));
2431 MUTILS_DELETE(metaInfoDialog);
2432 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
2433 sourceFilesScrollbarMoved(0);
2437 * Show context menu for source files
2439 void MainWindow::sourceFilesContextMenu(const QPoint &pos)
2441 QAbstractScrollArea *scrollArea = dynamic_cast<QAbstractScrollArea*>(QObject::sender());
2442 QWidget *sender = scrollArea ? scrollArea->viewport() : dynamic_cast<QWidget*>(QObject::sender());
2446 if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0)
2448 m_sourceFilesContextMenu->popup(sender->mapToGlobal(pos));
2454 * Scrollbar of source files moved
2456 void MainWindow::sourceFilesScrollbarMoved(int)
2458 ui->sourceFileView->resizeColumnToContents(0);
2462 * Open selected file in external player
2464 void MainWindow::previewContextActionTriggered(void)
2466 QModelIndex index = ui->sourceFileView->currentIndex();
2467 if(!index.isValid())
2472 if(!MUtils::OS::open_media_file(m_fileListModel->getFile(index).filePath()))
2474 qDebug("Player not found, falling back to default application...");
2475 QDesktopServices::openUrl(QString("file:///").append(m_fileListModel->getFile(index).filePath()));
2480 * Find selected file in explorer
2482 void MainWindow::findFileContextActionTriggered(void)
2484 QModelIndex index = ui->sourceFileView->currentIndex();
2487 QString systemRootPath;
2489 QDir systemRoot(MUtils::OS::known_folder(MUtils::OS::FOLDER_SYSTEMFOLDER));
2490 if(systemRoot.exists() && systemRoot.cdUp())
2492 systemRootPath = systemRoot.canonicalPath();
2495 if(!systemRootPath.isEmpty())
2497 QFileInfo explorer(QString("%1/explorer.exe").arg(systemRootPath));
2498 if(explorer.exists() && explorer.isFile())
2500 QProcess::execute(explorer.canonicalFilePath(), QStringList() << "/select," << QDir::toNativeSeparators(m_fileListModel->getFile(index).filePath()));
2506 qWarning("SystemRoot directory could not be detected!");
2512 * Add all dropped files
2514 void MainWindow::handleDroppedFiles(void)
2518 static const int MIN_COUNT = 16;
2519 const QString bannerText = tr("Loading dropped files or folders, please wait...");
2520 bool bUseBanner = false;
2522 SHOW_BANNER_CONDITIONALLY(bUseBanner, (m_droppedFileList->count() >= MIN_COUNT), bannerText);
2524 QStringList droppedFiles;
2525 while(!m_droppedFileList->isEmpty())
2527 QFileInfo file(m_droppedFileList->takeFirst().toLocalFile());
2528 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
2537 qDebug("Dropped File: %s", MUTILS_UTF8(file.canonicalFilePath()));
2538 droppedFiles << file.canonicalFilePath();
2544 qDebug("Dropped Folder: %s", MUTILS_UTF8(file.canonicalFilePath()));
2545 QFileInfoList list = QDir(file.canonicalFilePath()).entryInfoList(QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks);
2546 if(list.count() > 0)
2548 SHOW_BANNER_CONDITIONALLY(bUseBanner, (list.count() >= MIN_COUNT), bannerText);
2549 for(QFileInfoList::ConstIterator iter = list.constBegin(); iter != list.constEnd(); iter++)
2551 droppedFiles << (*iter).canonicalFilePath();
2556 list = QDir(file.canonicalFilePath()).entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks);
2557 SHOW_BANNER_CONDITIONALLY(bUseBanner, (list.count() >= MIN_COUNT), bannerText);
2558 for(QFileInfoList::ConstIterator iter = list.constBegin(); iter != list.constEnd(); iter++)
2560 qDebug("Descending to Folder: %s", MUTILS_UTF8((*iter).canonicalFilePath()));
2561 m_droppedFileList->prepend(QUrl::fromLocalFile((*iter).canonicalFilePath()));
2572 if(!droppedFiles.isEmpty())
2574 addFiles(droppedFiles);
2579 * Add all pending files
2581 void MainWindow::handleDelayedFiles(void)
2583 m_delayedFileTimer->stop();
2585 if(m_delayedFileList->isEmpty())
2592 m_delayedFileTimer->start(5000);
2596 WITH_BLOCKED_SIGNALS(ui->tabWidget, setCurrentIndex, 0);
2597 tabPageChanged(ui->tabWidget->currentIndex(), true);
2599 QStringList selectedFiles;
2600 while(!m_delayedFileList->isEmpty())
2602 QFileInfo currentFile = QFileInfo(m_delayedFileList->takeFirst());
2603 if(!currentFile.exists() || !currentFile.isFile())
2607 selectedFiles << currentFile.canonicalFilePath();
2610 addFiles(selectedFiles);
2614 * Export Meta tags to CSV file
2616 void MainWindow::exportCsvContextActionTriggered(void)
2620 QString selectedCsvFile;
2622 if(MUtils::GUI::themes_enabled())
2624 selectedCsvFile = QFileDialog::getSaveFileName(this, tr("Save CSV file"), m_settings->mostRecentInputPath(), QString("%1 (*.csv)").arg(tr("CSV File")));
2628 QFileDialog dialog(this, tr("Save CSV file"));
2629 dialog.setFileMode(QFileDialog::AnyFile);
2630 dialog.setAcceptMode(QFileDialog::AcceptSave);
2631 dialog.setNameFilter(QString("%1 (*.csv)").arg(tr("CSV File")));
2632 dialog.setDirectory(m_settings->mostRecentInputPath());
2635 selectedCsvFile = dialog.selectedFiles().first();
2639 if(!selectedCsvFile.isEmpty())
2641 m_settings->mostRecentInputPath(QFileInfo(selectedCsvFile).canonicalPath());
2642 switch(m_fileListModel->exportToCsv(selectedCsvFile))
2644 case FileListModel::CsvError_NoTags:
2645 QMessageBox::critical(this, tr("CSV Export"), NOBR(tr("Sorry, there are no meta tags that can be exported!")));
2647 case FileListModel::CsvError_FileOpen:
2648 QMessageBox::critical(this, tr("CSV Export"), NOBR(tr("Sorry, failed to open CSV file for writing!")));
2650 case FileListModel::CsvError_FileWrite:
2651 QMessageBox::critical(this, tr("CSV Export"), NOBR(tr("Sorry, failed to write to the CSV file!")));
2653 case FileListModel::CsvError_OK:
2654 QMessageBox::information(this, tr("CSV Export"), NOBR(tr("The CSV files was created successfully!")));
2657 qWarning("exportToCsv: Unknown return code!");
2665 * Import Meta tags from CSV file
2667 void MainWindow::importCsvContextActionTriggered(void)
2671 QString selectedCsvFile;
2673 if(MUtils::GUI::themes_enabled())
2675 selectedCsvFile = QFileDialog::getOpenFileName(this, tr("Open CSV file"), m_settings->mostRecentInputPath(), QString("%1 (*.csv)").arg(tr("CSV File")));
2679 QFileDialog dialog(this, tr("Open CSV file"));
2680 dialog.setFileMode(QFileDialog::ExistingFile);
2681 dialog.setNameFilter(QString("%1 (*.csv)").arg(tr("CSV File")));
2682 dialog.setDirectory(m_settings->mostRecentInputPath());
2685 selectedCsvFile = dialog.selectedFiles().first();
2689 if(!selectedCsvFile.isEmpty())
2691 m_settings->mostRecentInputPath(QFileInfo(selectedCsvFile).canonicalPath());
2692 switch(m_fileListModel->importFromCsv(this, selectedCsvFile))
2694 case FileListModel::CsvError_FileOpen:
2695 QMessageBox::critical(this, tr("CSV Import"), NOBR(tr("Sorry, failed to open CSV file for reading!")));
2697 case FileListModel::CsvError_FileRead:
2698 QMessageBox::critical(this, tr("CSV Import"), NOBR(tr("Sorry, failed to read from the CSV file!")));
2700 case FileListModel::CsvError_NoTags:
2701 QMessageBox::critical(this, tr("CSV Import"), NOBR(tr("Sorry, the CSV file does not contain any known fields!")));
2703 case FileListModel::CsvError_Incomplete:
2704 QMessageBox::warning(this, tr("CSV Import"), NOBR(tr("CSV file is incomplete. Not all files were updated!")));
2706 case FileListModel::CsvError_OK:
2707 QMessageBox::information(this, tr("CSV Import"), NOBR(tr("The CSV files was imported successfully!")));
2709 case FileListModel::CsvError_Aborted:
2710 /* User aborted, ignore! */
2713 qWarning("exportToCsv: Unknown return code!");
2720 * Show or hide Drag'n'Drop notice after model reset
2722 void MainWindow::sourceModelChanged(void)
2724 m_dropNoteLabel->setVisible(m_fileListModel->rowCount() <= 0);
2727 // =========================================================
2728 // Output folder slots
2729 // =========================================================
2732 * Output folder changed (mouse clicked)
2734 void MainWindow::outputFolderViewClicked(const QModelIndex &index)
2736 if(index.isValid() && (ui->outputFolderView->currentIndex() != index))
2738 ui->outputFolderView->setCurrentIndex(index);
2741 if(m_fileSystemModel && index.isValid())
2743 QString selectedDir = m_fileSystemModel->filePath(index);
2744 if(selectedDir.length() < 3) selectedDir.append(QDir::separator());
2745 ui->outputFolderLabel->setText(QDir::toNativeSeparators(selectedDir));
2746 ui->outputFolderLabel->setToolTip(ui->outputFolderLabel->text());
2747 m_settings->outputDir(selectedDir);
2751 ui->outputFolderLabel->setText(QDir::toNativeSeparators(m_settings->outputDir()));
2752 ui->outputFolderLabel->setToolTip(ui->outputFolderLabel->text());
2757 * Output folder changed (mouse moved)
2759 void MainWindow::outputFolderViewMoved(const QModelIndex &index)
2761 if(QApplication::mouseButtons() & Qt::LeftButton)
2763 outputFolderViewClicked(index);
2768 * Goto desktop button
2770 void MainWindow::gotoDesktopButtonClicked(void)
2772 if(!m_fileSystemModel)
2774 qWarning("File system model not initialized yet!");
2778 QString desktopPath = QDesktopServices::storageLocation(QDesktopServices::DesktopLocation);
2780 if(!desktopPath.isEmpty() && QDir(desktopPath).exists())
2782 ui->outputFolderView->setCurrentIndex(m_fileSystemModel->index(desktopPath));
2783 outputFolderViewClicked(ui->outputFolderView->currentIndex());
2784 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2788 ui->buttonGotoDesktop->setEnabled(false);
2793 * Goto home folder button
2795 void MainWindow::gotoHomeFolderButtonClicked(void)
2797 if(!m_fileSystemModel)
2799 qWarning("File system model not initialized yet!");
2803 QString homePath = QDesktopServices::storageLocation(QDesktopServices::HomeLocation);
2805 if(!homePath.isEmpty() && QDir(homePath).exists())
2807 ui->outputFolderView->setCurrentIndex(m_fileSystemModel->index(homePath));
2808 outputFolderViewClicked(ui->outputFolderView->currentIndex());
2809 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2813 ui->buttonGotoHome->setEnabled(false);
2818 * Goto music folder button
2820 void MainWindow::gotoMusicFolderButtonClicked(void)
2822 if(!m_fileSystemModel)
2824 qWarning("File system model not initialized yet!");
2828 QString musicPath = QDesktopServices::storageLocation(QDesktopServices::MusicLocation);
2830 if(!musicPath.isEmpty() && QDir(musicPath).exists())
2832 ui->outputFolderView->setCurrentIndex(m_fileSystemModel->index(musicPath));
2833 outputFolderViewClicked(ui->outputFolderView->currentIndex());
2834 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2838 ui->buttonGotoMusic->setEnabled(false);
2843 * Goto music favorite output folder
2845 void MainWindow::gotoFavoriteFolder(void)
2847 if(!m_fileSystemModel)
2849 qWarning("File system model not initialized yet!");
2853 QAction *item = dynamic_cast<QAction*>(QObject::sender());
2857 QDir path(item->data().toString());
2860 ui->outputFolderView->setCurrentIndex(m_fileSystemModel->index(path.canonicalPath()));
2861 outputFolderViewClicked(ui->outputFolderView->currentIndex());
2862 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2866 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
2867 m_outputFolderFavoritesMenu->removeAction(item);
2868 item->deleteLater();
2874 * Make folder button
2876 void MainWindow::makeFolderButtonClicked(void)
2880 if(!m_fileSystemModel)
2882 qWarning("File system model not initialized yet!");
2886 QDir basePath(m_fileSystemModel->fileInfo(ui->outputFolderView->currentIndex()).absoluteFilePath());
2887 QString suggestedName = tr("New Folder");
2889 if(!m_metaData->artist().isEmpty() && !m_metaData->album().isEmpty())
2891 suggestedName = QString("%1 - %2").arg(m_metaData->artist(),m_metaData->album());
2893 else if(!m_metaData->artist().isEmpty())
2895 suggestedName = m_metaData->artist();
2897 else if(!m_metaData->album().isEmpty())
2899 suggestedName =m_metaData->album();
2903 for(int i = 0; i < m_fileListModel->rowCount(); i++)
2905 const AudioFileModel &audioFile = m_fileListModel->getFile(m_fileListModel->index(i, 0));
2906 const AudioFileModel_MetaInfo &fileMetaInfo = audioFile.metaInfo();
2908 if(!fileMetaInfo.album().isEmpty() || !fileMetaInfo.artist().isEmpty())
2910 if(!fileMetaInfo.artist().isEmpty() && !fileMetaInfo.album().isEmpty())
2912 suggestedName = QString("%1 - %2").arg(fileMetaInfo.artist(), fileMetaInfo.album());
2914 else if(!fileMetaInfo.artist().isEmpty())
2916 suggestedName = fileMetaInfo.artist();
2918 else if(!fileMetaInfo.album().isEmpty())
2920 suggestedName = fileMetaInfo.album();
2927 suggestedName = MUtils::clean_file_name(suggestedName);
2931 bool bApplied = false;
2932 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();
2936 folderName = MUtils::clean_file_path(folderName.simplified());
2938 if(folderName.isEmpty())
2940 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
2945 QString newFolder = folderName;
2947 while(basePath.exists(newFolder))
2949 newFolder = QString(folderName).append(QString().sprintf(" (%d)", ++i));
2952 if(basePath.mkpath(newFolder))
2954 QDir createdDir = basePath;
2955 if(createdDir.cd(newFolder))
2957 QModelIndex newIndex = m_fileSystemModel->index(createdDir.canonicalPath());
2958 ui->outputFolderView->setCurrentIndex(newIndex);
2959 outputFolderViewClicked(newIndex);
2960 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2965 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!")));
2973 * Output to source dir changed
2975 void MainWindow::saveToSourceFolderChanged(void)
2977 m_settings->outputToSourceDir(ui->saveToSourceFolderCheckBox->isChecked());
2981 * Prepend relative source file path to output file name changed
2983 void MainWindow::prependRelativePathChanged(void)
2985 m_settings->prependRelativeSourcePath(ui->prependRelativePathCheckBox->isChecked());
2989 * Show context menu for output folder
2991 void MainWindow::outputFolderContextMenu(const QPoint &pos)
2993 QAbstractScrollArea *scrollArea = dynamic_cast<QAbstractScrollArea*>(QObject::sender());
2994 QWidget *sender = scrollArea ? scrollArea->viewport() : dynamic_cast<QWidget*>(QObject::sender());
2996 if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0)
2998 m_outputFolderContextMenu->popup(sender->mapToGlobal(pos));
3003 * Show selected folder in explorer
3005 void MainWindow::showFolderContextActionTriggered(void)
3007 if(!m_fileSystemModel)
3009 qWarning("File system model not initialized yet!");
3013 QString path = QDir::toNativeSeparators(m_fileSystemModel->filePath(ui->outputFolderView->currentIndex()));
3014 if(!path.endsWith(QDir::separator())) path.append(QDir::separator());
3015 MUtils::OS::shell_open(this, path, true);
3019 * Refresh the directory outline
3021 void MainWindow::refreshFolderContextActionTriggered(void)
3023 //force re-initialization
3024 QTimer::singleShot(0, this, SLOT(initOutputFolderModel()));
3028 * Go one directory up
3030 void MainWindow::goUpFolderContextActionTriggered(void)
3032 QModelIndex current = ui->outputFolderView->currentIndex();
3033 if(current.isValid())
3035 QModelIndex parent = current.parent();
3036 if(parent.isValid())
3039 ui->outputFolderView->setCurrentIndex(parent);
3040 outputFolderViewClicked(parent);
3044 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN);
3046 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
3051 * Add current folder to favorites
3053 void MainWindow::addFavoriteFolderActionTriggered(void)
3055 QString path = m_fileSystemModel->filePath(ui->outputFolderView->currentIndex());
3056 QStringList favorites = m_settings->favoriteOutputFolders().split("|", QString::SkipEmptyParts);
3058 if(!favorites.contains(path, Qt::CaseInsensitive))
3060 favorites.append(path);
3061 while(favorites.count() > 6) favorites.removeFirst();
3065 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN);
3068 m_settings->favoriteOutputFolders(favorites.join("|"));
3073 * Output folder edit finished
3075 void MainWindow::outputFolderEditFinished(void)
3077 if(ui->outputFolderEdit->isHidden())
3079 return; //Not currently in edit mode!
3084 QString text = QDir::fromNativeSeparators(ui->outputFolderEdit->text().trimmed());
3085 while(text.startsWith('"') || text.startsWith('/')) text = text.right(text.length() - 1).trimmed();
3086 while(text.endsWith('"') || text.endsWith('/')) text = text.left(text.length() - 1).trimmed();
3088 static const char *str = "?*<>|\"";
3089 for(size_t i = 0; str[i]; i++) text.replace(str[i], "_");
3091 if(!((text.length() >= 2) && text.at(0).isLetter() && text.at(1) == QChar(':')))
3093 text = QString("%1/%2").arg(QDir::fromNativeSeparators(ui->outputFolderLabel->text()), text);
3096 if(text.length() == 2) text += "/"; /* "X:" => "X:/" */
3098 while(text.length() > 2)
3100 QFileInfo info(text);
3101 if(info.exists() && info.isDir())
3103 QModelIndex index = m_fileSystemModel->index(QFileInfo(info.canonicalFilePath()).absoluteFilePath());
3107 ui->outputFolderView->setCurrentIndex(index);
3108 outputFolderViewClicked(index);
3112 else if(info.exists() && info.isFile())
3114 QModelIndex index = m_fileSystemModel->index(QFileInfo(info.canonicalPath()).absoluteFilePath());
3118 ui->outputFolderView->setCurrentIndex(index);
3119 outputFolderViewClicked(index);
3124 text = text.left(text.length() - 1).trimmed();
3127 ui->outputFolderEdit->setVisible(false);
3128 ui->outputFolderLabel->setVisible(true);
3129 ui->outputFolderView->setEnabled(true);
3131 if(!ok) MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
3132 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
3136 * Initialize file system model
3138 void MainWindow::initOutputFolderModel(void)
3140 if(m_outputFolderNoteBox->isHidden())
3142 m_outputFolderNoteBox->show();
3143 m_outputFolderNoteBox->repaint();
3144 m_outputFolderViewInitCounter = 4;
3146 if(m_fileSystemModel)
3148 SET_MODEL(ui->outputFolderView, NULL);
3149 MUTILS_DELETE(m_fileSystemModel);
3150 ui->outputFolderView->repaint();
3153 if(m_fileSystemModel = new QFileSystemModelEx())
3155 m_fileSystemModel->installEventFilter(this);
3156 connect(m_fileSystemModel, SIGNAL(directoryLoaded(QString)), this, SLOT(outputFolderDirectoryLoaded(QString)));
3157 connect(m_fileSystemModel, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(outputFolderRowsInserted(QModelIndex,int,int)));
3159 SET_MODEL(ui->outputFolderView, m_fileSystemModel);
3160 ui->outputFolderView->header()->setStretchLastSection(true);
3161 ui->outputFolderView->header()->hideSection(1);
3162 ui->outputFolderView->header()->hideSection(2);
3163 ui->outputFolderView->header()->hideSection(3);
3165 m_fileSystemModel->setRootPath("");
3166 QModelIndex index = m_fileSystemModel->index(m_settings->outputDir());
3167 if(index.isValid()) ui->outputFolderView->setCurrentIndex(index);
3168 outputFolderViewClicked(ui->outputFolderView->currentIndex());
3171 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
3172 QTimer::singleShot(125, this, SLOT(initOutputFolderModel_doAsync()));
3177 * Initialize file system model (do NOT call this one directly!)
3179 void MainWindow::initOutputFolderModel_doAsync(void)
3181 if(m_outputFolderViewInitCounter > 0)
3183 m_outputFolderViewInitCounter--;
3184 QTimer::singleShot(125, this, SLOT(initOutputFolderModel_doAsync()));
3188 QTimer::singleShot(125, m_outputFolderNoteBox, SLOT(hide()));
3189 ui->outputFolderView->setFocus();
3194 * Center current folder in view
3196 void MainWindow::centerOutputFolderModel(void)
3198 if(ui->outputFolderView->isVisible())
3200 centerOutputFolderModel_doAsync();
3201 QTimer::singleShot(125, this, SLOT(centerOutputFolderModel_doAsync()));
3206 * Center current folder in view (do NOT call this one directly!)
3208 void MainWindow::centerOutputFolderModel_doAsync(void)
3210 if(ui->outputFolderView->isVisible())
3212 m_outputFolderViewCentering = true;
3213 const QModelIndex index = ui->outputFolderView->currentIndex();
3214 ui->outputFolderView->scrollTo(index, QAbstractItemView::PositionAtCenter);
3215 ui->outputFolderView->setFocus();
3220 * File system model asynchronously loaded a dir
3222 void MainWindow::outputFolderDirectoryLoaded(const QString &path)
3224 if(m_outputFolderViewCentering)
3226 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
3231 * File system model inserted new items
3233 void MainWindow::outputFolderRowsInserted(const QModelIndex &parent, int start, int end)
3235 if(m_outputFolderViewCentering)
3237 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
3242 * Directory view item was expanded by user
3244 void MainWindow::outputFolderItemExpanded(const QModelIndex &item)
3246 //We need to stop centering as soon as the user has expanded an item manually!
3247 m_outputFolderViewCentering = false;
3251 * View event for output folder control occurred
3253 void MainWindow::outputFolderViewEventOccurred(QWidget *sender, QEvent *event)
3255 switch(event->type())
3259 case QEvent::KeyPress:
3260 case QEvent::KeyRelease:
3261 case QEvent::FocusIn:
3262 case QEvent::FocusOut:
3263 case QEvent::TouchEnd:
3264 outputFolderViewClicked(ui->outputFolderView->currentIndex());
3270 * Mouse event for output folder control occurred
3272 void MainWindow::outputFolderMouseEventOccurred(QWidget *sender, QEvent *event)
3274 QMouseEvent *mouseEvent = dynamic_cast<QMouseEvent*>(event);
3275 QPoint pos = (mouseEvent) ? mouseEvent->pos() : QPoint();
3277 if(sender == ui->outputFolderLabel)
3279 switch(event->type())
3281 case QEvent::MouseButtonPress:
3282 if(mouseEvent && (mouseEvent->button() == Qt::LeftButton))
3284 QString path = ui->outputFolderLabel->text();
3285 if(!path.endsWith(QDir::separator())) path.append(QDir::separator());
3286 MUtils::OS::shell_open(this, path, true);
3290 ui->outputFolderLabel->setForegroundRole(QPalette::Link);
3293 ui->outputFolderLabel->setForegroundRole(QPalette::WindowText);
3298 if((sender == ui->outputFoldersFovoritesLabel) || (sender == ui->outputFoldersEditorLabel) || (sender == ui->outputFoldersGoUpLabel))
3300 const type_info &styleType = typeid(*qApp->style());
3301 if((typeid(QPlastiqueStyle) == styleType) || (typeid(QWindowsStyle) == styleType))
3303 switch(event->type())
3306 dynamic_cast<QLabel*>(sender)->setFrameShadow(ui->outputFolderView->isEnabled() ? QFrame::Raised : QFrame::Plain);
3308 case QEvent::MouseButtonPress:
3309 dynamic_cast<QLabel*>(sender)->setFrameShadow(ui->outputFolderView->isEnabled() ? QFrame::Sunken : QFrame::Plain);
3311 case QEvent::MouseButtonRelease:
3312 dynamic_cast<QLabel*>(sender)->setFrameShadow(ui->outputFolderView->isEnabled() ? QFrame::Raised : QFrame::Plain);
3315 dynamic_cast<QLabel*>(sender)->setFrameShadow(ui->outputFolderView->isEnabled() ? QFrame::Plain : QFrame::Plain);
3321 dynamic_cast<QLabel*>(sender)->setFrameShadow(QFrame::Plain);
3324 if((event->type() == QEvent::MouseButtonRelease) && ui->outputFolderView->isEnabled() && (mouseEvent))
3326 if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0 && mouseEvent->button() != Qt::MidButton)
3328 if(sender == ui->outputFoldersFovoritesLabel)
3330 m_outputFolderFavoritesMenu->popup(sender->mapToGlobal(pos));
3332 else if(sender == ui->outputFoldersEditorLabel)
3334 ui->outputFolderView->setEnabled(false);
3335 ui->outputFolderLabel->setVisible(false);
3336 ui->outputFolderEdit->setVisible(true);
3337 ui->outputFolderEdit->setText(ui->outputFolderLabel->text());
3338 ui->outputFolderEdit->selectAll();
3339 ui->outputFolderEdit->setFocus();
3341 else if(sender == ui->outputFoldersGoUpLabel)
3343 QTimer::singleShot(0, this, SLOT(goUpFolderContextActionTriggered()));
3347 MUTILS_THROW("Oups, this is not supposed to happen!");
3354 // =========================================================
3355 // Metadata tab slots
3356 // =========================================================
3359 * Edit meta button clicked
3361 void MainWindow::editMetaButtonClicked(void)
3365 const QModelIndex index = ui->metaDataView->currentIndex();
3369 m_metaInfoModel->editItem(index, this);
3371 if(index.row() == 4)
3373 m_settings->metaInfoPosition(m_metaData->position());
3379 * Reset meta button clicked
3381 void MainWindow::clearMetaButtonClicked(void)
3384 m_metaInfoModel->clearData();
3388 * Meta tags enabled changed
3390 void MainWindow::metaTagsEnabledChanged(void)
3392 m_settings->writeMetaTags(ui->writeMetaDataCheckBox->isChecked());
3396 * Playlist enabled changed
3398 void MainWindow::playlistEnabledChanged(void)
3400 m_settings->createPlaylist(ui->generatePlaylistCheckBox->isChecked());
3403 // =========================================================
3404 // Compression tab slots
3405 // =========================================================
3410 void MainWindow::updateEncoder(int id)
3412 /*qWarning("\nupdateEncoder(%d)", id);*/
3414 m_settings->compressionEncoder(id);
3415 const AbstractEncoderInfo *info = EncoderRegistry::getEncoderInfo(id);
3417 //Update UI controls
3418 ui->radioButtonModeQuality ->setEnabled(info->isModeSupported(SettingsModel::VBRMode));
3419 ui->radioButtonModeAverageBitrate->setEnabled(info->isModeSupported(SettingsModel::ABRMode));
3420 ui->radioButtonConstBitrate ->setEnabled(info->isModeSupported(SettingsModel::CBRMode));
3422 //Initialize checkbox state
3423 if(ui->radioButtonModeQuality->isEnabled()) ui->radioButtonModeQuality->setChecked(true);
3424 else if(ui->radioButtonModeAverageBitrate->isEnabled()) ui->radioButtonModeAverageBitrate->setChecked(true);
3425 else if(ui->radioButtonConstBitrate->isEnabled()) ui->radioButtonConstBitrate->setChecked(true);
3426 else MUTILS_THROW("It appears that the encoder does not support *any* RC mode!");
3428 //Apply current RC mode
3429 const int currentRCMode = EncoderRegistry::loadEncoderMode(m_settings, id);
3430 switch(currentRCMode)
3432 case SettingsModel::VBRMode: if(ui->radioButtonModeQuality->isEnabled()) ui->radioButtonModeQuality->setChecked(true); break;
3433 case SettingsModel::ABRMode: if(ui->radioButtonModeAverageBitrate->isEnabled()) ui->radioButtonModeAverageBitrate->setChecked(true); break;
3434 case SettingsModel::CBRMode: if(ui->radioButtonConstBitrate->isEnabled()) ui->radioButtonConstBitrate->setChecked(true); break;
3435 default: MUTILS_THROW("updateEncoder(): Unknown rc-mode encountered!");
3438 //Display encoder description
3439 if(const char* description = info->description())
3441 ui->labelEncoderInfo->setVisible(true);
3442 ui->labelEncoderInfo->setText(tr("Current Encoder: %1").arg(QString::fromUtf8(description)));
3446 ui->labelEncoderInfo->setVisible(false);
3450 updateRCMode(m_modeButtonGroup->checkedId());
3454 * Update rate-control mode
3456 void MainWindow::updateRCMode(int id)
3458 /*qWarning("updateRCMode(%d)", id);*/
3461 const int currentEncoder = m_encoderButtonGroup->checkedId();
3462 EncoderRegistry::saveEncoderMode(m_settings, currentEncoder, id);
3464 //Fetch encoder info
3465 const AbstractEncoderInfo *info = EncoderRegistry::getEncoderInfo(currentEncoder);
3466 const int valueCount = info->valueCount(id);
3469 if(!info->isModeSupported(id))
3471 qWarning("Attempting to use an unsupported RC mode (%d) with current encoder (%d)!", id, currentEncoder);
3472 ui->labelBitrate->setText("(ERROR)");
3476 //Update slider min/max values
3479 WITH_BLOCKED_SIGNALS(ui->sliderBitrate, setEnabled, true);
3480 WITH_BLOCKED_SIGNALS(ui->sliderBitrate, setMinimum, 0);
3481 WITH_BLOCKED_SIGNALS(ui->sliderBitrate, setMaximum, valueCount-1);
3485 WITH_BLOCKED_SIGNALS(ui->sliderBitrate, setEnabled, false);
3486 WITH_BLOCKED_SIGNALS(ui->sliderBitrate, setMinimum, 0);
3487 WITH_BLOCKED_SIGNALS(ui->sliderBitrate, setMaximum, 2);
3490 //Now update bitrate/quality value!
3493 const int currentValue = EncoderRegistry::loadEncoderValue(m_settings, currentEncoder, id);
3494 ui->sliderBitrate->setValue(qBound(0, currentValue, valueCount-1));
3495 updateBitrate(qBound(0, currentValue, valueCount-1));
3499 ui->sliderBitrate->setValue(1);
3507 void MainWindow::updateBitrate(int value)
3509 /*qWarning("updateBitrate(%d)", value);*/
3511 //Load current encoder and RC mode
3512 const int currentEncoder = m_encoderButtonGroup->checkedId();
3513 const int currentRCMode = m_modeButtonGroup->checkedId();
3515 //Fetch encoder info
3516 const AbstractEncoderInfo *info = EncoderRegistry::getEncoderInfo(currentEncoder);
3517 const int valueCount = info->valueCount(currentRCMode);
3520 if(!info->isModeSupported(currentRCMode))
3522 qWarning("Attempting to use an unsupported RC mode (%d) with current encoder (%d)!", currentRCMode, currentEncoder);
3523 ui->labelBitrate->setText("(ERROR)");
3527 //Store new bitrate value
3530 EncoderRegistry::saveEncoderValue(m_settings, currentEncoder, currentRCMode, qBound(0, value, valueCount-1));
3533 //Update bitrate value
3534 const int displayValue = (valueCount > 0) ? info->valueAt(currentRCMode, qBound(0, value, valueCount-1)) : INT_MAX;
3535 switch(info->valueType(currentRCMode))
3537 case AbstractEncoderInfo::TYPE_BITRATE:
3538 ui->labelBitrate->setText(QString("%1 kbps").arg(QString::number(displayValue)));
3540 case AbstractEncoderInfo::TYPE_APPROX_BITRATE:
3541 ui->labelBitrate->setText(QString("≈ %1 kbps").arg(QString::number(displayValue)));
3543 case AbstractEncoderInfo::TYPE_QUALITY_LEVEL_INT:
3544 ui->labelBitrate->setText(tr("Quality Level %1").arg(QString::number(displayValue)));
3546 case AbstractEncoderInfo::TYPE_QUALITY_LEVEL_FLT:
3547 ui->labelBitrate->setText(tr("Quality Level %1").arg(QString().sprintf("%.2f", double(displayValue)/100.0)));
3549 case AbstractEncoderInfo::TYPE_COMPRESSION_LEVEL:
3550 ui->labelBitrate->setText(tr("Compression %1").arg(QString::number(displayValue)));
3552 case AbstractEncoderInfo::TYPE_UNCOMPRESSED:
3553 ui->labelBitrate->setText(tr("Uncompressed"));
3556 MUTILS_THROW("Unknown display value type encountered!");
3562 * Event for compression tab occurred
3564 void MainWindow::compressionTabEventOccurred(QWidget *sender, QEvent *event)
3566 static const QUrl helpUrl("http://lamexp.sourceforge.net/doc/FAQ.html#054010d9");
3568 if((sender == ui->labelCompressionHelp) && (event->type() == QEvent::MouseButtonPress))
3570 QDesktopServices::openUrl(helpUrl);
3572 else if((sender == ui->labelResetEncoders) && (event->type() == QEvent::MouseButtonPress))
3574 PLAY_SOUND_OPTIONAL("blast", true);
3575 EncoderRegistry::resetAllEncoders(m_settings);
3576 m_settings->compressionEncoder(SettingsModel::MP3Encoder);
3577 ui->radioButtonEncoderMP3->setChecked(true);
3578 QTimer::singleShot(0, this, SLOT(updateEncoder()));
3582 // =========================================================
3583 // Advanced option slots
3584 // =========================================================
3587 * Lame algorithm quality changed
3589 void MainWindow::updateLameAlgoQuality(int value)
3596 text = tr("Best Quality (Slow)");
3599 text = tr("High Quality (Recommended)");
3602 text = tr("Acceptable Quality (Fast)");
3605 text = tr("Poor Quality (Very Fast)");
3611 m_settings->lameAlgoQuality(value);
3612 ui->labelLameAlgoQuality->setText(text);
3615 bool warning = (value == 0), notice = (value == 3);
3616 ui->labelLameAlgoQualityWarning->setVisible(warning);
3617 ui->labelLameAlgoQualityWarningIcon->setVisible(warning);
3618 ui->labelLameAlgoQualityNotice->setVisible(notice);
3619 ui->labelLameAlgoQualityNoticeIcon->setVisible(notice);
3620 ui->labelLameAlgoQualitySpacer->setVisible(warning || notice);
3624 * Bitrate management endabled/disabled
3626 void MainWindow::bitrateManagementEnabledChanged(bool checked)
3628 m_settings->bitrateManagementEnabled(checked);
3632 * Minimum bitrate has changed
3634 void MainWindow::bitrateManagementMinChanged(int value)
3636 if(value > ui->spinBoxBitrateManagementMax->value())
3638 ui->spinBoxBitrateManagementMin->setValue(ui->spinBoxBitrateManagementMax->value());
3639 m_settings->bitrateManagementMinRate(ui->spinBoxBitrateManagementMax->value());
3643 m_settings->bitrateManagementMinRate(value);
3648 * Maximum bitrate has changed
3650 void MainWindow::bitrateManagementMaxChanged(int value)
3652 if(value < ui->spinBoxBitrateManagementMin->value())
3654 ui->spinBoxBitrateManagementMax->setValue(ui->spinBoxBitrateManagementMin->value());
3655 m_settings->bitrateManagementMaxRate(ui->spinBoxBitrateManagementMin->value());
3659 m_settings->bitrateManagementMaxRate(value);
3664 * Channel mode has changed
3666 void MainWindow::channelModeChanged(int value)
3668 if(value >= 0) m_settings->lameChannelMode(value);
3672 * Sampling rate has changed
3674 void MainWindow::samplingRateChanged(int value)
3676 if(value >= 0) m_settings->samplingRate(value);
3680 * Nero AAC 2-Pass mode changed
3682 void MainWindow::neroAAC2PassChanged(bool checked)
3684 m_settings->neroAACEnable2Pass(checked);
3688 * Nero AAC profile mode changed
3690 void MainWindow::neroAACProfileChanged(int value)
3692 if(value >= 0) m_settings->aacEncProfile(value);
3696 * Aften audio coding mode changed
3698 void MainWindow::aftenCodingModeChanged(int value)
3700 if(value >= 0) m_settings->aftenAudioCodingMode(value);
3704 * Aften DRC mode changed
3706 void MainWindow::aftenDRCModeChanged(int value)
3708 if(value >= 0) m_settings->aftenDynamicRangeCompression(value);
3712 * Aften exponent search size changed
3714 void MainWindow::aftenSearchSizeChanged(int value)
3716 if(value >= 0) m_settings->aftenExponentSearchSize(value);
3720 * Aften fast bit allocation changed
3722 void MainWindow::aftenFastAllocationChanged(bool checked)
3724 m_settings->aftenFastBitAllocation(checked);
3729 * Opus encoder settings changed
3731 void MainWindow::opusSettingsChanged(void)
3733 m_settings->opusFramesize(ui->comboBoxOpusFramesize->currentIndex());
3734 m_settings->opusComplexity(ui->spinBoxOpusComplexity->value());
3735 m_settings->opusDisableResample(ui->checkBoxOpusDisableResample->isChecked());
3739 * Normalization filter enabled changed
3741 void MainWindow::normalizationEnabledChanged(bool checked)
3743 m_settings->normalizationFilterEnabled(checked);
3747 * Normalization max. volume changed
3749 void MainWindow::normalizationMaxVolumeChanged(double value)
3751 m_settings->normalizationFilterMaxVolume(static_cast<int>(value * 100.0));
3755 * Normalization equalization mode changed
3757 void MainWindow::normalizationModeChanged(int mode)
3759 m_settings->normalizationFilterEQMode(mode);
3763 * Tone adjustment has changed (Bass)
3765 void MainWindow::toneAdjustBassChanged(double value)
3767 m_settings->toneAdjustBass(static_cast<int>(value * 100.0));
3768 ui->spinBoxToneAdjustBass->setPrefix((value > 0) ? "+" : QString());
3772 * Tone adjustment has changed (Treble)
3774 void MainWindow::toneAdjustTrebleChanged(double value)
3776 m_settings->toneAdjustTreble(static_cast<int>(value * 100.0));
3777 ui->spinBoxToneAdjustTreble->setPrefix((value > 0) ? "+" : QString());
3781 * Tone adjustment has been reset
3783 void MainWindow::toneAdjustTrebleReset(void)
3785 ui->spinBoxToneAdjustBass->setValue(m_settings->toneAdjustBassDefault());
3786 ui->spinBoxToneAdjustTreble->setValue(m_settings->toneAdjustTrebleDefault());
3787 toneAdjustBassChanged(ui->spinBoxToneAdjustBass->value());
3788 toneAdjustTrebleChanged(ui->spinBoxToneAdjustTreble->value());
3792 * Custom encoder parameters changed
3794 void MainWindow::customParamsChanged(void)
3796 ui->lineEditCustomParamLAME->setText(ui->lineEditCustomParamLAME->text().simplified());
3797 ui->lineEditCustomParamOggEnc->setText(ui->lineEditCustomParamOggEnc->text().simplified());
3798 ui->lineEditCustomParamNeroAAC->setText(ui->lineEditCustomParamNeroAAC->text().simplified());
3799 ui->lineEditCustomParamFLAC->setText(ui->lineEditCustomParamFLAC->text().simplified());
3800 ui->lineEditCustomParamAften->setText(ui->lineEditCustomParamAften->text().simplified());
3801 ui->lineEditCustomParamOpus->setText(ui->lineEditCustomParamOpus->text().simplified());
3803 bool customParamsUsed = false;
3804 if(!ui->lineEditCustomParamLAME->text().isEmpty()) customParamsUsed = true;
3805 if(!ui->lineEditCustomParamOggEnc->text().isEmpty()) customParamsUsed = true;
3806 if(!ui->lineEditCustomParamNeroAAC->text().isEmpty()) customParamsUsed = true;
3807 if(!ui->lineEditCustomParamFLAC->text().isEmpty()) customParamsUsed = true;
3808 if(!ui->lineEditCustomParamAften->text().isEmpty()) customParamsUsed = true;
3809 if(!ui->lineEditCustomParamOpus->text().isEmpty()) customParamsUsed = true;
3811 ui->labelCustomParamsIcon->setVisible(customParamsUsed);
3812 ui->labelCustomParamsText->setVisible(customParamsUsed);
3813 ui->labelCustomParamsSpacer->setVisible(customParamsUsed);
3815 EncoderRegistry::saveEncoderCustomParams(m_settings, SettingsModel::MP3Encoder, ui->lineEditCustomParamLAME->text());
3816 EncoderRegistry::saveEncoderCustomParams(m_settings, SettingsModel::VorbisEncoder, ui->lineEditCustomParamOggEnc->text());
3817 EncoderRegistry::saveEncoderCustomParams(m_settings, SettingsModel::AACEncoder, ui->lineEditCustomParamNeroAAC->text());
3818 EncoderRegistry::saveEncoderCustomParams(m_settings, SettingsModel::FLACEncoder, ui->lineEditCustomParamFLAC->text());
3819 EncoderRegistry::saveEncoderCustomParams(m_settings, SettingsModel::AC3Encoder, ui->lineEditCustomParamAften->text());
3820 EncoderRegistry::saveEncoderCustomParams(m_settings, SettingsModel::OpusEncoder, ui->lineEditCustomParamOpus->text());
3824 * Rename output files enabled changed
3826 void MainWindow::renameOutputEnabledChanged(bool checked)
3828 m_settings->renameOutputFilesEnabled(checked);
3832 * Rename output files patterm changed
3834 void MainWindow::renameOutputPatternChanged(void)
3836 QString temp = ui->lineEditRenamePattern->text().simplified();
3837 ui->lineEditRenamePattern->setText(temp.isEmpty() ? m_settings->renameOutputFilesPatternDefault() : temp);
3838 m_settings->renameOutputFilesPattern(ui->lineEditRenamePattern->text());
3842 * Rename output files patterm changed
3844 void MainWindow::renameOutputPatternChanged(const QString &text, bool silent)
3846 QString pattern(text.simplified());
3848 pattern.replace("<BaseName>", "The_White_Stripes_-_Fell_In_Love_With_A_Girl", Qt::CaseInsensitive);
3849 pattern.replace("<TrackNo>", "04", Qt::CaseInsensitive);
3850 pattern.replace("<Title>", "Fell In Love With A Girl", Qt::CaseInsensitive);
3851 pattern.replace("<Artist>", "The White Stripes", Qt::CaseInsensitive);
3852 pattern.replace("<Album>", "White Blood Cells", Qt::CaseInsensitive);
3853 pattern.replace("<Year>", "2001", Qt::CaseInsensitive);
3854 pattern.replace("<Comment>", "Encoded by LameXP", Qt::CaseInsensitive);
3856 const QString patternClean = MUtils::clean_file_name(pattern);
3858 if(pattern.compare(patternClean))
3860 if(ui->lineEditRenamePattern->palette().color(QPalette::Text) != Qt::red)
3862 if(!silent) MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
3863 SET_TEXT_COLOR(ui->lineEditRenamePattern, Qt::red);
3868 if(ui->lineEditRenamePattern->palette() != QPalette())
3870 if(!silent) MUtils::Sound::beep(MUtils::Sound::BEEP_NFO);
3871 ui->lineEditRenamePattern->setPalette(QPalette());
3875 ui->labelRanameExample->setText(patternClean);
3879 * Show list of rename macros
3881 void MainWindow::showRenameMacros(const QString &text)
3883 if(text.compare("reset", Qt::CaseInsensitive) == 0)
3885 ui->lineEditRenamePattern->setText(m_settings->renameOutputFilesPatternDefault());
3889 const QString format = QString("<tr><td><tt><%1></tt></td><td> </td><td>%2</td></tr>");
3891 QString message = QString("<table>");
3892 message += QString(format).arg("BaseName", tr("File name without extension"));
3893 message += QString(format).arg("TrackNo", tr("Track number with leading zero"));
3894 message += QString(format).arg("Title", tr("Track title"));
3895 message += QString(format).arg("Artist", tr("Artist name"));
3896 message += QString(format).arg("Album", tr("Album name"));
3897 message += QString(format).arg("Year", tr("Year with (at least) four digits"));
3898 message += QString(format).arg("Comment", tr("Comment"));
3899 message += "</table><br><br>";
3900 message += QString("%1<br>").arg(tr("Characters forbidden in file names:"));
3901 message += "<b><tt>\\ / : * ? < > |<br>";
3903 QMessageBox::information(this, tr("Rename Macros"), message, tr("Discard"));
3906 void MainWindow::forceStereoDownmixEnabledChanged(bool checked)
3908 m_settings->forceStereoDownmix(checked);
3912 * Maximum number of instances changed
3914 void MainWindow::updateMaximumInstances(int value)
3916 ui->labelMaxInstances->setText(tr("%n Instance(s)", "", value));
3917 m_settings->maximumInstances(ui->checkBoxAutoDetectInstances->isChecked() ? NULL : value);
3921 * Auto-detect number of instances
3923 void MainWindow::autoDetectInstancesChanged(bool checked)
3925 m_settings->maximumInstances(checked ? NULL : ui->sliderMaxInstances->value());
3929 * Browse for custom TEMP folder button clicked
3931 void MainWindow::browseCustomTempFolderButtonClicked(void)
3933 QString newTempFolder;
3935 if(MUtils::GUI::themes_enabled())
3937 newTempFolder = QFileDialog::getExistingDirectory(this, QString(), m_settings->customTempPath());
3941 QFileDialog dialog(this);
3942 dialog.setFileMode(QFileDialog::DirectoryOnly);
3943 dialog.setDirectory(m_settings->customTempPath());
3946 newTempFolder = dialog.selectedFiles().first();
3950 if(!newTempFolder.isEmpty())
3952 QFile writeTest(QString("%1/~%2.tmp").arg(newTempFolder, MUtils::rand_str()));
3953 if(writeTest.open(QIODevice::ReadWrite))
3956 ui->lineEditCustomTempFolder->setText(QDir::toNativeSeparators(newTempFolder));
3960 QMessageBox::warning(this, tr("Access Denied"), tr("Cannot write to the selected directory. Please choose another directory!"));
3966 * Custom TEMP folder changed
3968 void MainWindow::customTempFolderChanged(const QString &text)
3970 m_settings->customTempPath(QDir::fromNativeSeparators(text));
3974 * Use custom TEMP folder option changed
3976 void MainWindow::useCustomTempFolderChanged(bool checked)
3978 m_settings->customTempPathEnabled(!checked);
3982 * Help for custom parameters was requested
3984 void MainWindow::customParamsHelpRequested(QWidget *obj, QEvent *event)
3986 if(event->type() != QEvent::MouseButtonRelease)
3991 if(QMouseEvent *mouseEvent = dynamic_cast<QMouseEvent*>(event))
3993 QPoint pos = mouseEvent->pos();
3994 if(!(pos.x() <= obj->width() && pos.y() <= obj->height() && pos.x() >= 0 && pos.y() >= 0 && mouseEvent->button() != Qt::MidButton))
4000 if(obj == ui->helpCustomParamLAME) showCustomParamsHelpScreen("lame.exe", "--longhelp");
4001 else if(obj == ui->helpCustomParamOggEnc) showCustomParamsHelpScreen("oggenc2.exe", "--help");
4002 else if(obj == ui->helpCustomParamNeroAAC)
4004 switch(EncoderRegistry::getAacEncoder())
4006 case SettingsModel::AAC_ENCODER_QAAC: showCustomParamsHelpScreen("qaac.exe", "--help"); break;
4007 case SettingsModel::AAC_ENCODER_FHG : showCustomParamsHelpScreen("fhgaacenc.exe", ""); break;
4008 case SettingsModel::AAC_ENCODER_NERO: showCustomParamsHelpScreen("neroAacEnc.exe", "-help"); break;
4009 default: MUtils::Sound::beep(MUtils::Sound::BEEP_ERR); break;
4012 else if(obj == ui->helpCustomParamFLAC) showCustomParamsHelpScreen("flac.exe", "--help");
4013 else if(obj == ui->helpCustomParamAften) showCustomParamsHelpScreen("aften.exe", "-h");
4014 else if(obj == ui->helpCustomParamOpus) showCustomParamsHelpScreen("opusenc.exe", "--help");
4015 else MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
4019 * Show help for custom parameters
4021 void MainWindow::showCustomParamsHelpScreen(const QString &toolName, const QString &command)
4023 const QString binary = lamexp_tools_lookup(toolName);
4024 if(binary.isEmpty())
4026 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
4027 qWarning("customParamsHelpRequested: Binary could not be found!");
4032 MUtils::init_process(process, QFileInfo(binary).absolutePath());
4034 process.start(binary, command.isEmpty() ? QStringList() : QStringList() << command);
4036 qApp->setOverrideCursor(QCursor(Qt::WaitCursor));
4038 if(process.waitForStarted(15000))
4040 qApp->processEvents();
4041 process.waitForFinished(15000);
4044 if(process.state() != QProcess::NotRunning)
4047 process.waitForFinished(-1);
4050 qApp->restoreOverrideCursor();
4051 QStringList output; bool spaceFlag = true;
4053 while(process.canReadLine())
4055 QString temp = QString::fromUtf8(process.readLine());
4056 TRIM_STRING_RIGHT(temp);
4059 if(!spaceFlag) { output << temp; spaceFlag = true; }
4063 output << temp; spaceFlag = false;
4067 if(output.count() < 1)
4069 qWarning("Empty output, cannot show help screen!");
4070 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
4073 LogViewDialog *dialog = new LogViewDialog(this);
4074 TEMP_HIDE_DROPBOX( dialog->exec(output); );
4075 MUTILS_DELETE(dialog);
4078 void MainWindow::overwriteModeChanged(int id)
4080 if((id == SettingsModel::Overwrite_Replaces) && (m_settings->overwriteMode() != SettingsModel::Overwrite_Replaces))
4082 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)
4084 ui->radioButtonOverwriteModeKeepBoth->setChecked(m_settings->overwriteMode() == SettingsModel::Overwrite_KeepBoth);
4085 ui->radioButtonOverwriteModeSkipFile->setChecked(m_settings->overwriteMode() == SettingsModel::Overwrite_SkipFile);
4090 m_settings->overwriteMode(id);
4094 * Reset all advanced options to their defaults
4096 void MainWindow::resetAdvancedOptionsButtonClicked(void)
4098 PLAY_SOUND_OPTIONAL("blast", true);
4100 ui->sliderLameAlgoQuality->setValue(m_settings->lameAlgoQualityDefault());
4101 ui->spinBoxBitrateManagementMin->setValue(m_settings->bitrateManagementMinRateDefault());
4102 ui->spinBoxBitrateManagementMax->setValue(m_settings->bitrateManagementMaxRateDefault());
4103 ui->spinBoxNormalizationFilter->setValue(static_cast<double>(m_settings->normalizationFilterMaxVolumeDefault()) / 100.0);
4104 ui->spinBoxToneAdjustBass->setValue(static_cast<double>(m_settings->toneAdjustBassDefault()) / 100.0);
4105 ui->spinBoxToneAdjustTreble->setValue(static_cast<double>(m_settings->toneAdjustTrebleDefault()) / 100.0);
4106 ui->spinBoxAftenSearchSize->setValue(m_settings->aftenExponentSearchSizeDefault());
4107 ui->spinBoxOpusComplexity->setValue(m_settings->opusComplexityDefault());
4108 ui->comboBoxMP3ChannelMode->setCurrentIndex(m_settings->lameChannelModeDefault());
4109 ui->comboBoxSamplingRate->setCurrentIndex(m_settings->samplingRateDefault());
4110 ui->comboBoxAACProfile->setCurrentIndex(m_settings->aacEncProfileDefault());
4111 ui->comboBoxAftenCodingMode->setCurrentIndex(m_settings->aftenAudioCodingModeDefault());
4112 ui->comboBoxAftenDRCMode->setCurrentIndex(m_settings->aftenDynamicRangeCompressionDefault());
4113 ui->comboBoxNormalizationMode->setCurrentIndex(m_settings->normalizationFilterEQModeDefault());
4114 ui->comboBoxOpusFramesize->setCurrentIndex(m_settings->opusFramesizeDefault());
4116 SET_CHECKBOX_STATE(ui->checkBoxBitrateManagement, m_settings->bitrateManagementEnabledDefault());
4117 SET_CHECKBOX_STATE(ui->checkBoxNeroAAC2PassMode, m_settings->neroAACEnable2PassDefault());
4118 SET_CHECKBOX_STATE(ui->checkBoxNormalizationFilter, m_settings->normalizationFilterEnabledDefault());
4119 SET_CHECKBOX_STATE(ui->checkBoxAutoDetectInstances, (m_settings->maximumInstancesDefault() < 1));
4120 SET_CHECKBOX_STATE(ui->checkBoxUseSystemTempFolder, !m_settings->customTempPathEnabledDefault());
4121 SET_CHECKBOX_STATE(ui->checkBoxAftenFastAllocation, m_settings->aftenFastBitAllocationDefault());
4122 SET_CHECKBOX_STATE(ui->checkBoxRenameOutput, m_settings->renameOutputFilesEnabledDefault());
4123 SET_CHECKBOX_STATE(ui->checkBoxForceStereoDownmix, m_settings->forceStereoDownmixDefault());
4124 SET_CHECKBOX_STATE(ui->checkBoxOpusDisableResample, m_settings->opusDisableResampleDefault());
4126 ui->lineEditCustomParamLAME ->setText(m_settings->customParametersLAMEDefault());
4127 ui->lineEditCustomParamOggEnc ->setText(m_settings->customParametersOggEncDefault());
4128 ui->lineEditCustomParamNeroAAC->setText(m_settings->customParametersAacEncDefault());
4129 ui->lineEditCustomParamFLAC ->setText(m_settings->customParametersFLACDefault());
4130 ui->lineEditCustomParamOpus ->setText(m_settings->customParametersOpusEncDefault());
4131 ui->lineEditCustomTempFolder ->setText(QDir::toNativeSeparators(m_settings->customTempPathDefault()));
4132 ui->lineEditRenamePattern ->setText(m_settings->renameOutputFilesPatternDefault());
4134 if(m_settings->overwriteModeDefault() == SettingsModel::Overwrite_KeepBoth) ui->radioButtonOverwriteModeKeepBoth->click();
4135 if(m_settings->overwriteModeDefault() == SettingsModel::Overwrite_SkipFile) ui->radioButtonOverwriteModeSkipFile->click();
4136 if(m_settings->overwriteModeDefault() == SettingsModel::Overwrite_Replaces) ui->radioButtonOverwriteModeReplaces->click();
4138 customParamsChanged();
4139 ui->scrollArea->verticalScrollBar()->setValue(0);
4142 // =========================================================
4143 // Multi-instance handling slots
4144 // =========================================================
4147 * Other instance detected
4149 void MainWindow::notifyOtherInstance(void)
4151 if(!(BANNER_VISIBLE))
4153 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);
4159 * Add file from another instance
4161 void MainWindow::addFileDelayed(const QString &filePath, bool tryASAP)
4163 if(tryASAP && !m_delayedFileTimer->isActive())
4165 qDebug("Received file: %s", MUTILS_UTF8(filePath));
4166 m_delayedFileList->append(filePath);
4167 QTimer::singleShot(0, this, SLOT(handleDelayedFiles()));
4170 m_delayedFileTimer->stop();
4171 qDebug("Received file: %s", MUTILS_UTF8(filePath));
4172 m_delayedFileList->append(filePath);
4173 m_delayedFileTimer->start(5000);
4177 * Add files from another instance
4179 void MainWindow::addFilesDelayed(const QStringList &filePaths, bool tryASAP)
4181 if(tryASAP && (!m_delayedFileTimer->isActive()))
4183 qDebug("Received %d file(s).", filePaths.count());
4184 m_delayedFileList->append(filePaths);
4185 QTimer::singleShot(0, this, SLOT(handleDelayedFiles()));
4189 m_delayedFileTimer->stop();
4190 qDebug("Received %d file(s).", filePaths.count());
4191 m_delayedFileList->append(filePaths);
4192 m_delayedFileTimer->start(5000);
4197 * Add folder from another instance
4199 void MainWindow::addFolderDelayed(const QString &folderPath, bool recursive)
4201 if(!(BANNER_VISIBLE))
4203 addFolder(folderPath, recursive, true);
4207 // =========================================================
4209 // =========================================================
4212 * Restore the override cursor
4214 void MainWindow::restoreCursor(void)
4216 QApplication::restoreOverrideCursor();