Actually make RegExp-based file renaming work.
[LameXP.git] / src / Dialog_MainWindow.cpp
blob623bc76c88ff4da9ef26e3a138e4135d3fde2674
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2015 LoRd_MuldeR <MuldeR2@GMX.de>
4 //
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; either version 2 of the License, or
8 // (at your option) any later version, but always including the *additional*
9 // restrictions defined in the "License.txt" file.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License along
17 // with this program; if not, write to the Free Software Foundation, Inc.,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 // http://www.gnu.org/licenses/gpl-2.0.txt
21 ///////////////////////////////////////////////////////////////////////////////
23 #include "Dialog_MainWindow.h"
25 //UIC includes
26 #include "UIC_MainWindow.h"
28 //LameXP includes
29 #include "Global.h"
30 #include "Dialog_WorkingBanner.h"
31 #include "Dialog_MetaInfo.h"
32 #include "Dialog_About.h"
33 #include "Dialog_Update.h"
34 #include "Dialog_DropBox.h"
35 #include "Dialog_CueImport.h"
36 #include "Dialog_LogView.h"
37 #include "Thread_FileAnalyzer.h"
38 #include "Thread_MessageHandler.h"
39 #include "Model_MetaInfo.h"
40 #include "Model_Settings.h"
41 #include "Model_FileList.h"
42 #include "Model_FileSystem.h"
43 #include "Registry_Encoder.h"
44 #include "Registry_Decoder.h"
45 #include "Encoder_Abstract.h"
46 #include "ShellIntegration.h"
47 #include "CustomEventFilter.h"
49 //Mutils includes
50 #include <MUtils/Global.h>
51 #include <MUtils/OSSupport.h>
52 #include <MUtils/GUI.h>
53 #include <MUtils/Exception.h>
54 #include <MUtils/Sound.h>
55 #include <MUtils/Translation.h>
56 #include <MUtils/Version.h>
58 //Qt includes
59 #include <QMessageBox>
60 #include <QTimer>
61 #include <QDesktopWidget>
62 #include <QDate>
63 #include <QFileDialog>
64 #include <QInputDialog>
65 #include <QFileSystemModel>
66 #include <QDesktopServices>
67 #include <QUrl>
68 #include <QPlastiqueStyle>
69 #include <QCleanlooksStyle>
70 #include <QWindowsVistaStyle>
71 #include <QWindowsStyle>
72 #include <QSysInfo>
73 #include <QDragEnterEvent>
74 #include <QMimeData>
75 #include <QProcess>
76 #include <QUuid>
77 #include <QProcessEnvironment>
78 #include <QCryptographicHash>
79 #include <QTranslator>
80 #include <QResource>
81 #include <QScrollBar>
83 ////////////////////////////////////////////////////////////
84 // Helper macros
85 ////////////////////////////////////////////////////////////
87 #define BANNER_VISIBLE ((m_banner != NULL) && m_banner->isVisible())
89 #define INIT_BANNER() do \
90 { \
91 if(m_banner == NULL) \
92 { \
93 m_banner = new WorkingBanner(this); \
94 } \
95 } \
96 while(0)
98 #define SHOW_BANNER(TXT) do \
99 { \
100 INIT_BANNER(); \
101 m_banner->show((TXT)); \
103 while(0)
105 #define SHOW_BANNER_ARG(TXT, ARG) do \
107 INIT_BANNER(); \
108 m_banner->show((TXT), (ARG)); \
110 while(0)
113 #define SHOW_BANNER_CONDITIONALLY(FLAG, TEST, TXT) do \
115 if((!(FLAG)) && ((TEST))) \
117 INIT_BANNER(); \
118 m_banner->show((TXT)); \
119 FLAG = true; \
122 while(0)
124 #define ABORT_IF_BUSY do \
126 if(BANNER_VISIBLE || m_delayedFileTimer->isActive() || (QApplication::activeModalWidget() != NULL)) \
128 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN); \
129 return; \
132 while(0)
134 #define SET_TEXT_COLOR(WIDGET, COLOR) do \
136 QPalette _palette = WIDGET->palette(); \
137 _palette.setColor(QPalette::WindowText, (COLOR)); \
138 _palette.setColor(QPalette::Text, (COLOR)); \
139 WIDGET->setPalette(_palette); \
141 while(0)
143 #define SET_FONT_BOLD(WIDGET,BOLD) do \
145 QFont _font = WIDGET->font(); \
146 _font.setBold(BOLD); \
147 WIDGET->setFont(_font); \
149 while(0)
151 #define TEMP_HIDE_DROPBOX(CMD) do \
153 bool _dropBoxVisible = m_dropBox->isVisible(); \
154 if(_dropBoxVisible) m_dropBox->hide(); \
155 do { CMD } while(0); \
156 if(_dropBoxVisible) m_dropBox->show(); \
158 while(0)
160 #define SET_MODEL(VIEW, MODEL) do \
162 QItemSelectionModel *_tmp = (VIEW)->selectionModel(); \
163 (VIEW)->setModel(MODEL); \
164 MUTILS_DELETE(_tmp); \
166 while(0)
168 #define SET_CHECKBOX_STATE(CHCKBX, STATE) do \
170 const bool isDisabled = (!(CHCKBX)->isEnabled()); \
171 if(isDisabled) \
173 (CHCKBX)->setEnabled(true); \
175 if((CHCKBX)->isChecked() != (STATE)) \
177 (CHCKBX)->click(); \
179 if((CHCKBX)->isChecked() != (STATE)) \
181 qWarning("Warning: Failed to set checkbox " #CHCKBX " state!"); \
183 if(isDisabled) \
185 (CHCKBX)->setEnabled(false); \
188 while(0)
190 #define TRIM_STRING_RIGHT(STR) do \
192 while((STR.length() > 0) && STR[STR.length()-1].isSpace()) STR.chop(1); \
194 while(0)
196 #define MAKE_TRANSPARENT(WIDGET, FLAG) do \
198 QPalette _p = (WIDGET)->palette(); \
199 _p.setColor(QPalette::Background, Qt::transparent); \
200 (WIDGET)->setPalette(FLAG ? _p : QPalette()); \
202 while(0)
204 #define WITH_BLOCKED_SIGNALS(WIDGET, CMD, ...) do \
206 const bool _flag = (WIDGET)->blockSignals(true); \
207 (WIDGET)->CMD(__VA_ARGS__); \
208 if(!(_flag)) { (WIDGET)->blockSignals(false); } \
210 while(0)
212 #define PLAY_SOUND_OPTIONAL(NAME, ASYNC) do \
214 if(m_settings->soundsEnabled()) MUtils::Sound::play_sound((NAME), (ASYNC)); \
216 while(0)
218 #define SHOW_CORNER_WIDGET(FLAG) do \
220 if(QWidget *cornerWidget = ui->menubar->cornerWidget()) \
222 cornerWidget->setVisible((FLAG)); \
225 while(0)
227 #define LINK(URL) QString("<a href=\"%1\">%2</a>").arg(URL).arg(QString(URL).replace("-", "&minus;"))
228 #define FSLINK(PATH) QString("<a href=\"file:///%1\">%2</a>").arg(PATH).arg(QString(PATH).replace("-", "&minus;"))
229 #define CENTER_CURRENT_OUTPUT_FOLDER_DELAYED QTimer::singleShot(125, this, SLOT(centerOutputFolderModel()))
231 static const unsigned int IDM_ABOUTBOX = 0xEFF0;
232 static const char *g_hydrogen_audio_url = "http://wiki.hydrogenaud.io/index.php?title=Main_Page";
233 static const char *g_documents_base_url = "http://lamexp.sourceforge.net/doc";
235 ////////////////////////////////////////////////////////////
236 // Constructor
237 ////////////////////////////////////////////////////////////
239 MainWindow::MainWindow(MUtils::IPCChannel *const ipcChannel, FileListModel *const fileListModel, AudioFileModel_MetaInfo *const metaInfo, SettingsModel *const settingsModel, QWidget *const parent)
241 QMainWindow(parent),
242 ui(new Ui::MainWindow),
243 m_fileListModel(fileListModel),
244 m_metaData(metaInfo),
245 m_settings(settingsModel),
246 m_fileSystemModel(NULL),
247 m_banner(NULL),
248 m_accepted(false),
249 m_firstTimeShown(true),
250 m_outputFolderViewCentering(false),
251 m_outputFolderViewInitCounter(0)
253 //Init the dialog, from the .ui file
254 ui->setupUi(this);
255 setWindowFlags(windowFlags() ^ Qt::WindowMaximizeButtonHint);
257 //Create window icon
258 MUtils::GUI::set_window_icon(this, lamexp_app_icon(), true);
260 //Register meta types
261 qRegisterMetaType<AudioFileModel>("AudioFileModel");
263 //Enabled main buttons
264 connect(ui->buttonAbout, SIGNAL(clicked()), this, SLOT(aboutButtonClicked()));
265 connect(ui->buttonStart, SIGNAL(clicked()), this, SLOT(encodeButtonClicked()));
266 connect(ui->buttonQuit, SIGNAL(clicked()), this, SLOT(closeButtonClicked()));
268 //Setup tab widget
269 ui->tabWidget->setCurrentIndex(0);
270 connect(ui->tabWidget, SIGNAL(currentChanged(int)), this, SLOT(tabPageChanged(int)));
272 //Add system menu
273 MUtils::GUI::sysmenu_append(this, IDM_ABOUTBOX, "About...");
275 //Setup corner widget
276 QLabel *cornerWidget = new QLabel(ui->menubar);
277 m_evenFilterCornerWidget = new CustomEventFilter;
278 cornerWidget->setText("N/A");
279 cornerWidget->setFixedHeight(ui->menubar->height());
280 cornerWidget->setCursor(QCursor(Qt::PointingHandCursor));
281 cornerWidget->hide();
282 cornerWidget->installEventFilter(m_evenFilterCornerWidget);
283 connect(m_evenFilterCornerWidget, SIGNAL(eventOccurred(QWidget*, QEvent*)), this, SLOT(cornerWidgetEventOccurred(QWidget*, QEvent*)));
284 ui->menubar->setCornerWidget(cornerWidget);
286 //--------------------------------
287 // Setup "Source" tab
288 //--------------------------------
290 ui->sourceFileView->setModel(m_fileListModel);
291 ui->sourceFileView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
292 ui->sourceFileView->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);
293 ui->sourceFileView->setContextMenuPolicy(Qt::CustomContextMenu);
294 ui->sourceFileView->viewport()->installEventFilter(this);
295 m_dropNoteLabel = new QLabel(ui->sourceFileView);
296 m_dropNoteLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
297 SET_FONT_BOLD(m_dropNoteLabel, true);
298 SET_TEXT_COLOR(m_dropNoteLabel, Qt::darkGray);
299 m_sourceFilesContextMenu = new QMenu();
300 m_showDetailsContextAction = m_sourceFilesContextMenu->addAction(QIcon(":/icons/zoom.png"), "N/A");
301 m_previewContextAction = m_sourceFilesContextMenu->addAction(QIcon(":/icons/sound.png"), "N/A");
302 m_findFileContextAction = m_sourceFilesContextMenu->addAction(QIcon(":/icons/folder_go.png"), "N/A");
303 m_sourceFilesContextMenu->addSeparator();
304 m_exportCsvContextAction = m_sourceFilesContextMenu->addAction(QIcon(":/icons/table_save.png"), "N/A");
305 m_importCsvContextAction = m_sourceFilesContextMenu->addAction(QIcon(":/icons/folder_table.png"), "N/A");
306 SET_FONT_BOLD(m_showDetailsContextAction, true);
308 connect(ui->buttonAddFiles, SIGNAL(clicked()), this, SLOT(addFilesButtonClicked()));
309 connect(ui->buttonRemoveFile, SIGNAL(clicked()), this, SLOT(removeFileButtonClicked()));
310 connect(ui->buttonClearFiles, SIGNAL(clicked()), this, SLOT(clearFilesButtonClicked()));
311 connect(ui->buttonFileUp, SIGNAL(clicked()), this, SLOT(fileUpButtonClicked()));
312 connect(ui->buttonFileDown, SIGNAL(clicked()), this, SLOT(fileDownButtonClicked()));
313 connect(ui->buttonShowDetails, SIGNAL(clicked()), this, SLOT(showDetailsButtonClicked()));
314 connect(m_fileListModel, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(sourceModelChanged()));
315 connect(m_fileListModel, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(sourceModelChanged()));
316 connect(m_fileListModel, SIGNAL(modelReset()), this, SLOT(sourceModelChanged()));
317 connect(ui->sourceFileView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(sourceFilesContextMenu(QPoint)));
318 connect(ui->sourceFileView->verticalScrollBar(), SIGNAL(sliderMoved(int)), this, SLOT(sourceFilesScrollbarMoved(int)));
319 connect(ui->sourceFileView->verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(sourceFilesScrollbarMoved(int)));
320 connect(m_showDetailsContextAction, SIGNAL(triggered(bool)), this, SLOT(showDetailsButtonClicked()));
321 connect(m_previewContextAction, SIGNAL(triggered(bool)), this, SLOT(previewContextActionTriggered()));
322 connect(m_findFileContextAction, SIGNAL(triggered(bool)), this, SLOT(findFileContextActionTriggered()));
323 connect(m_exportCsvContextAction, SIGNAL(triggered(bool)), this, SLOT(exportCsvContextActionTriggered()));
324 connect(m_importCsvContextAction, SIGNAL(triggered(bool)), this, SLOT(importCsvContextActionTriggered()));
326 //--------------------------------
327 // Setup "Output" tab
328 //--------------------------------
330 ui->outputFolderView->setHeaderHidden(true);
331 ui->outputFolderView->setAnimated(false);
332 ui->outputFolderView->setMouseTracking(false);
333 ui->outputFolderView->setContextMenuPolicy(Qt::CustomContextMenu);
334 ui->outputFolderView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
336 m_evenFilterOutputFolderMouse = new CustomEventFilter;
337 ui->outputFoldersGoUpLabel->installEventFilter(m_evenFilterOutputFolderMouse);
338 ui->outputFoldersEditorLabel->installEventFilter(m_evenFilterOutputFolderMouse);
339 ui->outputFoldersFovoritesLabel->installEventFilter(m_evenFilterOutputFolderMouse);
340 ui->outputFolderLabel->installEventFilter(m_evenFilterOutputFolderMouse);
342 m_evenFilterOutputFolderView = new CustomEventFilter;
343 ui->outputFolderView->installEventFilter(m_evenFilterOutputFolderView);
345 SET_CHECKBOX_STATE(ui->saveToSourceFolderCheckBox, m_settings->outputToSourceDir());
346 ui->prependRelativePathCheckBox->setChecked(m_settings->prependRelativeSourcePath());
348 connect(ui->outputFolderView, SIGNAL(clicked(QModelIndex)), this, SLOT(outputFolderViewClicked(QModelIndex)));
349 connect(ui->outputFolderView, SIGNAL(activated(QModelIndex)), this, SLOT(outputFolderViewClicked(QModelIndex)));
350 connect(ui->outputFolderView, SIGNAL(pressed(QModelIndex)), this, SLOT(outputFolderViewClicked(QModelIndex)));
351 connect(ui->outputFolderView, SIGNAL(entered(QModelIndex)), this, SLOT(outputFolderViewMoved(QModelIndex)));
352 connect(ui->outputFolderView, SIGNAL(expanded(QModelIndex)), this, SLOT(outputFolderItemExpanded(QModelIndex)));
353 connect(ui->buttonMakeFolder, SIGNAL(clicked()), this, SLOT(makeFolderButtonClicked()));
354 connect(ui->buttonGotoHome, SIGNAL(clicked()), SLOT(gotoHomeFolderButtonClicked()));
355 connect(ui->buttonGotoDesktop, SIGNAL(clicked()), this, SLOT(gotoDesktopButtonClicked()));
356 connect(ui->buttonGotoMusic, SIGNAL(clicked()), this, SLOT(gotoMusicFolderButtonClicked()));
357 connect(ui->saveToSourceFolderCheckBox, SIGNAL(clicked()), this, SLOT(saveToSourceFolderChanged()));
358 connect(ui->prependRelativePathCheckBox, SIGNAL(clicked()), this, SLOT(prependRelativePathChanged()));
359 connect(ui->outputFolderEdit, SIGNAL(editingFinished()), this, SLOT(outputFolderEditFinished()));
360 connect(m_evenFilterOutputFolderMouse, SIGNAL(eventOccurred(QWidget*, QEvent*)), this, SLOT(outputFolderMouseEventOccurred(QWidget*, QEvent*)));
361 connect(m_evenFilterOutputFolderView, SIGNAL(eventOccurred(QWidget*, QEvent*)), this, SLOT(outputFolderViewEventOccurred(QWidget*, QEvent*)));
363 if(m_outputFolderContextMenu = new QMenu())
365 m_showFolderContextAction = m_outputFolderContextMenu->addAction(QIcon(":/icons/zoom.png"), "N/A");
366 m_goUpFolderContextAction = m_outputFolderContextMenu->addAction(QIcon(":/icons/folder_up.png"), "N/A");
367 m_outputFolderContextMenu->addSeparator();
368 m_refreshFolderContextAction = m_outputFolderContextMenu->addAction(QIcon(":/icons/arrow_refresh.png"), "N/A");
369 m_outputFolderContextMenu->setDefaultAction(m_showFolderContextAction);
370 connect(ui->outputFolderView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(outputFolderContextMenu(QPoint)));
371 connect(m_showFolderContextAction, SIGNAL(triggered(bool)), this, SLOT(showFolderContextActionTriggered()));
372 connect(m_refreshFolderContextAction, SIGNAL(triggered(bool)), this, SLOT(refreshFolderContextActionTriggered()));
373 connect(m_goUpFolderContextAction, SIGNAL(triggered(bool)), this, SLOT(goUpFolderContextActionTriggered()));
376 if(m_outputFolderFavoritesMenu = new QMenu())
378 m_addFavoriteFolderAction = m_outputFolderFavoritesMenu->addAction(QIcon(":/icons/add.png"), "N/A");
379 m_outputFolderFavoritesMenu->insertSeparator(m_addFavoriteFolderAction);
380 connect(m_addFavoriteFolderAction, SIGNAL(triggered(bool)), this, SLOT(addFavoriteFolderActionTriggered()));
383 ui->outputFolderEdit->setVisible(false);
384 if(m_outputFolderNoteBox = new QLabel(ui->outputFolderView))
386 m_outputFolderNoteBox->setAutoFillBackground(true);
387 m_outputFolderNoteBox->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
388 m_outputFolderNoteBox->setFrameShape(QFrame::StyledPanel);
389 SET_FONT_BOLD(m_outputFolderNoteBox, true);
390 m_outputFolderNoteBox->hide();
394 outputFolderViewClicked(QModelIndex());
395 refreshFavorites();
397 //--------------------------------
398 // Setup "Meta Data" tab
399 //--------------------------------
401 m_metaInfoModel = new MetaInfoModel(m_metaData);
402 m_metaInfoModel->clearData();
403 m_metaInfoModel->setData(m_metaInfoModel->index(4, 1), m_settings->metaInfoPosition());
404 ui->metaDataView->setModel(m_metaInfoModel);
405 ui->metaDataView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
406 ui->metaDataView->verticalHeader()->hide();
407 ui->metaDataView->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);
408 SET_CHECKBOX_STATE(ui->writeMetaDataCheckBox, m_settings->writeMetaTags());
409 ui->generatePlaylistCheckBox->setChecked(m_settings->createPlaylist());
410 connect(ui->buttonEditMeta, SIGNAL(clicked()), this, SLOT(editMetaButtonClicked()));
411 connect(ui->buttonClearMeta, SIGNAL(clicked()), this, SLOT(clearMetaButtonClicked()));
412 connect(ui->writeMetaDataCheckBox, SIGNAL(clicked()), this, SLOT(metaTagsEnabledChanged()));
413 connect(ui->generatePlaylistCheckBox, SIGNAL(clicked()), this, SLOT(playlistEnabledChanged()));
415 //--------------------------------
416 //Setup "Compression" tab
417 //--------------------------------
419 m_encoderButtonGroup = new QButtonGroup(this);
420 m_encoderButtonGroup->addButton(ui->radioButtonEncoderMP3, SettingsModel::MP3Encoder);
421 m_encoderButtonGroup->addButton(ui->radioButtonEncoderVorbis, SettingsModel::VorbisEncoder);
422 m_encoderButtonGroup->addButton(ui->radioButtonEncoderAAC, SettingsModel::AACEncoder);
423 m_encoderButtonGroup->addButton(ui->radioButtonEncoderAC3, SettingsModel::AC3Encoder);
424 m_encoderButtonGroup->addButton(ui->radioButtonEncoderFLAC, SettingsModel::FLACEncoder);
425 m_encoderButtonGroup->addButton(ui->radioButtonEncoderAPE, SettingsModel::MACEncoder);
426 m_encoderButtonGroup->addButton(ui->radioButtonEncoderOpus, SettingsModel::OpusEncoder);
427 m_encoderButtonGroup->addButton(ui->radioButtonEncoderDCA, SettingsModel::DCAEncoder);
428 m_encoderButtonGroup->addButton(ui->radioButtonEncoderPCM, SettingsModel::PCMEncoder);
430 const int aacEncoder = EncoderRegistry::getAacEncoder();
431 ui->radioButtonEncoderAAC->setEnabled(aacEncoder > SettingsModel::AAC_ENCODER_NONE);
433 m_modeButtonGroup = new QButtonGroup(this);
434 m_modeButtonGroup->addButton(ui->radioButtonModeQuality, SettingsModel::VBRMode);
435 m_modeButtonGroup->addButton(ui->radioButtonModeAverageBitrate, SettingsModel::ABRMode);
436 m_modeButtonGroup->addButton(ui->radioButtonConstBitrate, SettingsModel::CBRMode);
438 ui->radioButtonEncoderMP3->setChecked(true);
439 foreach(QAbstractButton *currentButton, m_encoderButtonGroup->buttons())
441 if(currentButton->isEnabled() && (m_encoderButtonGroup->id(currentButton) == m_settings->compressionEncoder()))
443 currentButton->setChecked(true);
444 break;
448 m_evenFilterCompressionTab = new CustomEventFilter();
449 ui->labelCompressionHelp->installEventFilter(m_evenFilterCompressionTab);
450 ui->labelResetEncoders ->installEventFilter(m_evenFilterCompressionTab);
452 connect(m_encoderButtonGroup, SIGNAL(buttonClicked(int)), this, SLOT(updateEncoder(int)));
453 connect(m_modeButtonGroup, SIGNAL(buttonClicked(int)), this, SLOT(updateRCMode(int)));
454 connect(m_evenFilterCompressionTab, SIGNAL(eventOccurred(QWidget*, QEvent*)), this, SLOT(compressionTabEventOccurred(QWidget*, QEvent*)));
455 connect(ui->sliderBitrate, SIGNAL(valueChanged(int)), this, SLOT(updateBitrate(int)));
457 updateEncoder(m_encoderButtonGroup->checkedId());
459 //--------------------------------
460 //Setup "Advanced Options" tab
461 //--------------------------------
463 ui->sliderLameAlgoQuality->setValue(m_settings->lameAlgoQuality());
464 if(m_settings->maximumInstances() > 0) ui->sliderMaxInstances->setValue(m_settings->maximumInstances());
466 ui->spinBoxBitrateManagementMin ->setValue(m_settings->bitrateManagementMinRate());
467 ui->spinBoxBitrateManagementMax ->setValue(m_settings->bitrateManagementMaxRate());
468 ui->spinBoxNormalizationFilterPeak->setValue(static_cast<double>(m_settings->normalizationFilterMaxVolume()) / 100.0);
469 ui->spinBoxNormalizationFilterSize->setValue(m_settings->normalizationFilterSize());
470 ui->spinBoxToneAdjustBass ->setValue(static_cast<double>(m_settings->toneAdjustBass()) / 100.0);
471 ui->spinBoxToneAdjustTreble ->setValue(static_cast<double>(m_settings->toneAdjustTreble()) / 100.0);
472 ui->spinBoxAftenSearchSize ->setValue(m_settings->aftenExponentSearchSize());
473 ui->spinBoxOpusComplexity ->setValue(m_settings->opusComplexity());
475 ui->comboBoxMP3ChannelMode ->setCurrentIndex(m_settings->lameChannelMode());
476 ui->comboBoxSamplingRate ->setCurrentIndex(m_settings->samplingRate());
477 ui->comboBoxAACProfile ->setCurrentIndex(m_settings->aacEncProfile());
478 ui->comboBoxAftenCodingMode ->setCurrentIndex(m_settings->aftenAudioCodingMode());
479 ui->comboBoxAftenDRCMode ->setCurrentIndex(m_settings->aftenDynamicRangeCompression());
480 ui->comboBoxOpusFramesize ->setCurrentIndex(m_settings->opusFramesize());
482 SET_CHECKBOX_STATE(ui->checkBoxBitrateManagement, m_settings->bitrateManagementEnabled());
483 SET_CHECKBOX_STATE(ui->checkBoxNeroAAC2PassMode, m_settings->neroAACEnable2Pass());
484 SET_CHECKBOX_STATE(ui->checkBoxAftenFastAllocation, m_settings->aftenFastBitAllocation());
485 SET_CHECKBOX_STATE(ui->checkBoxNormalizationFilterEnabled, m_settings->normalizationFilterEnabled());
486 SET_CHECKBOX_STATE(ui->checkBoxNormalizationFilterDynamic, m_settings->normalizationFilterDynamic());
487 SET_CHECKBOX_STATE(ui->checkBoxNormalizationFilterCoupled, m_settings->normalizationFilterCoupled());
488 SET_CHECKBOX_STATE(ui->checkBoxAutoDetectInstances, (m_settings->maximumInstances() < 1));
489 SET_CHECKBOX_STATE(ui->checkBoxUseSystemTempFolder, (!m_settings->customTempPathEnabled()));
490 SET_CHECKBOX_STATE(ui->checkBoxRename_Rename, m_settings->renameFiles_renameEnabled());
491 SET_CHECKBOX_STATE(ui->checkBoxRename_RegExp, m_settings->renameFiles_regExpEnabled());
492 SET_CHECKBOX_STATE(ui->checkBoxForceStereoDownmix, m_settings->forceStereoDownmix());
493 SET_CHECKBOX_STATE(ui->checkBoxOpusDisableResample, m_settings->opusDisableResample());
495 ui->checkBoxNeroAAC2PassMode->setEnabled(aacEncoder == SettingsModel::AAC_ENCODER_NERO);
497 ui->lineEditCustomParamLAME ->setText(EncoderRegistry::loadEncoderCustomParams(m_settings, SettingsModel::MP3Encoder));
498 ui->lineEditCustomParamOggEnc ->setText(EncoderRegistry::loadEncoderCustomParams(m_settings, SettingsModel::VorbisEncoder));
499 ui->lineEditCustomParamNeroAAC ->setText(EncoderRegistry::loadEncoderCustomParams(m_settings, SettingsModel::AACEncoder));
500 ui->lineEditCustomParamFLAC ->setText(EncoderRegistry::loadEncoderCustomParams(m_settings, SettingsModel::FLACEncoder));
501 ui->lineEditCustomParamAften ->setText(EncoderRegistry::loadEncoderCustomParams(m_settings, SettingsModel::AC3Encoder));
502 ui->lineEditCustomParamOpus ->setText(EncoderRegistry::loadEncoderCustomParams(m_settings, SettingsModel::OpusEncoder));
503 ui->lineEditCustomTempFolder ->setText(QDir::toNativeSeparators(m_settings->customTempPath()));
504 ui->lineEditRenamePattern ->setText(m_settings->renameFiles_renamePattern());
505 ui->lineEditRenameRegExp_Search ->setText(m_settings->renameFiles_regExpSearch ());
506 ui->lineEditRenameRegExp_Replace->setText(m_settings->renameFiles_regExpReplace());
508 m_evenFilterCustumParamsHelp = new CustomEventFilter();
509 ui->helpCustomParamLAME->installEventFilter(m_evenFilterCustumParamsHelp);
510 ui->helpCustomParamOggEnc->installEventFilter(m_evenFilterCustumParamsHelp);
511 ui->helpCustomParamNeroAAC->installEventFilter(m_evenFilterCustumParamsHelp);
512 ui->helpCustomParamFLAC->installEventFilter(m_evenFilterCustumParamsHelp);
513 ui->helpCustomParamAften->installEventFilter(m_evenFilterCustumParamsHelp);
514 ui->helpCustomParamOpus->installEventFilter(m_evenFilterCustumParamsHelp);
516 m_overwriteButtonGroup = new QButtonGroup(this);
517 m_overwriteButtonGroup->addButton(ui->radioButtonOverwriteModeKeepBoth, SettingsModel::Overwrite_KeepBoth);
518 m_overwriteButtonGroup->addButton(ui->radioButtonOverwriteModeSkipFile, SettingsModel::Overwrite_SkipFile);
519 m_overwriteButtonGroup->addButton(ui->radioButtonOverwriteModeReplaces, SettingsModel::Overwrite_Replaces);
521 ui->radioButtonOverwriteModeKeepBoth->setChecked(m_settings->overwriteMode() == SettingsModel::Overwrite_KeepBoth);
522 ui->radioButtonOverwriteModeSkipFile->setChecked(m_settings->overwriteMode() == SettingsModel::Overwrite_SkipFile);
523 ui->radioButtonOverwriteModeReplaces->setChecked(m_settings->overwriteMode() == SettingsModel::Overwrite_Replaces);
525 connect(ui->sliderLameAlgoQuality, SIGNAL(valueChanged(int)), this, SLOT(updateLameAlgoQuality(int)));
526 connect(ui->checkBoxBitrateManagement, SIGNAL(clicked(bool)), this, SLOT(bitrateManagementEnabledChanged(bool)));
527 connect(ui->spinBoxBitrateManagementMin, SIGNAL(valueChanged(int)), this, SLOT(bitrateManagementMinChanged(int)));
528 connect(ui->spinBoxBitrateManagementMax, SIGNAL(valueChanged(int)), this, SLOT(bitrateManagementMaxChanged(int)));
529 connect(ui->comboBoxMP3ChannelMode, SIGNAL(currentIndexChanged(int)), this, SLOT(channelModeChanged(int)));
530 connect(ui->comboBoxSamplingRate, SIGNAL(currentIndexChanged(int)), this, SLOT(samplingRateChanged(int)));
531 connect(ui->checkBoxNeroAAC2PassMode, SIGNAL(clicked(bool)), this, SLOT(neroAAC2PassChanged(bool)));
532 connect(ui->comboBoxAACProfile, SIGNAL(currentIndexChanged(int)), this, SLOT(neroAACProfileChanged(int)));
533 connect(ui->checkBoxNormalizationFilterEnabled, SIGNAL(clicked(bool)), this, SLOT(normalizationEnabledChanged(bool)));
534 connect(ui->checkBoxNormalizationFilterDynamic, SIGNAL(clicked(bool)), this, SLOT(normalizationDynamicChanged(bool)));
535 connect(ui->checkBoxNormalizationFilterCoupled, SIGNAL(clicked(bool)), this, SLOT(normalizationCoupledChanged(bool)));
536 connect(ui->comboBoxAftenCodingMode, SIGNAL(currentIndexChanged(int)), this, SLOT(aftenCodingModeChanged(int)));
537 connect(ui->comboBoxAftenDRCMode, SIGNAL(currentIndexChanged(int)), this, SLOT(aftenDRCModeChanged(int)));
538 connect(ui->spinBoxAftenSearchSize, SIGNAL(valueChanged(int)), this, SLOT(aftenSearchSizeChanged(int)));
539 connect(ui->checkBoxAftenFastAllocation, SIGNAL(clicked(bool)), this, SLOT(aftenFastAllocationChanged(bool)));
540 connect(ui->spinBoxNormalizationFilterPeak, SIGNAL(valueChanged(double)), this, SLOT(normalizationMaxVolumeChanged(double)));
541 connect(ui->spinBoxNormalizationFilterSize, SIGNAL(valueChanged(int)), this, SLOT(normalizationFilterSizeChanged(int)));
542 connect(ui->spinBoxNormalizationFilterSize, SIGNAL(editingFinished()), this, SLOT(normalizationFilterSizeFinished()));
543 connect(ui->spinBoxToneAdjustBass, SIGNAL(valueChanged(double)), this, SLOT(toneAdjustBassChanged(double)));
544 connect(ui->spinBoxToneAdjustTreble, SIGNAL(valueChanged(double)), this, SLOT(toneAdjustTrebleChanged(double)));
545 connect(ui->buttonToneAdjustReset, SIGNAL(clicked()), this, SLOT(toneAdjustTrebleReset()));
546 connect(ui->lineEditCustomParamLAME, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
547 connect(ui->lineEditCustomParamOggEnc, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
548 connect(ui->lineEditCustomParamNeroAAC, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
549 connect(ui->lineEditCustomParamFLAC, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
550 connect(ui->lineEditCustomParamAften, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
551 connect(ui->lineEditCustomParamOpus, SIGNAL(editingFinished()), this, SLOT(customParamsChanged()));
552 connect(ui->sliderMaxInstances, SIGNAL(valueChanged(int)), this, SLOT(updateMaximumInstances(int)));
553 connect(ui->checkBoxAutoDetectInstances, SIGNAL(clicked(bool)), this, SLOT(autoDetectInstancesChanged(bool)));
554 connect(ui->buttonBrowseCustomTempFolder, SIGNAL(clicked()), this, SLOT(browseCustomTempFolderButtonClicked()));
555 connect(ui->lineEditCustomTempFolder, SIGNAL(textChanged(QString)), this, SLOT(customTempFolderChanged(QString)));
556 connect(ui->checkBoxUseSystemTempFolder, SIGNAL(clicked(bool)), this, SLOT(useCustomTempFolderChanged(bool)));
557 connect(ui->buttonResetAdvancedOptions, SIGNAL(clicked()), this, SLOT(resetAdvancedOptionsButtonClicked()));
558 connect(ui->checkBoxRename_Rename, SIGNAL(clicked(bool)), this, SLOT(renameOutputEnabledChanged(bool)));
559 connect(ui->checkBoxRename_RegExp, SIGNAL(clicked(bool)), this, SLOT(renameRegExpEnabledChanged(bool)));
560 connect(ui->lineEditRenamePattern, SIGNAL(editingFinished()), this, SLOT(renameOutputPatternChanged()));
561 connect(ui->lineEditRenamePattern, SIGNAL(textChanged(QString)), this, SLOT(renameOutputPatternChanged(QString)));
562 connect(ui->lineEditRenameRegExp_Search, SIGNAL(editingFinished()), this, SLOT(renameRegExpValueChanged()));
563 connect(ui->lineEditRenameRegExp_Search, SIGNAL(textChanged(QString)), this, SLOT(renameRegExpSearchChanged(QString)));
564 connect(ui->lineEditRenameRegExp_Replace, SIGNAL(editingFinished()), this, SLOT(renameRegExpValueChanged()));
565 connect(ui->lineEditRenameRegExp_Replace, SIGNAL(textChanged(QString)), this, SLOT(renameRegExpReplaceChanged(QString)));
566 connect(ui->labelShowRenameMacros, SIGNAL(linkActivated(QString)), this, SLOT(showRenameMacros(QString)));
567 connect(ui->labelShowRegExpHelp, SIGNAL(linkActivated(QString)), this, SLOT(showRenameMacros(QString)));
568 connect(ui->checkBoxForceStereoDownmix, SIGNAL(clicked(bool)), this, SLOT(forceStereoDownmixEnabledChanged(bool)));
569 connect(ui->comboBoxOpusFramesize, SIGNAL(currentIndexChanged(int)), this, SLOT(opusSettingsChanged()));
570 connect(ui->spinBoxOpusComplexity, SIGNAL(valueChanged(int)), this, SLOT(opusSettingsChanged()));
571 connect(ui->checkBoxOpusDisableResample, SIGNAL(clicked(bool)), this, SLOT(opusSettingsChanged()));
572 connect(ui->buttonRename_Rename, SIGNAL(clicked(bool)), this, SLOT(renameButtonClicked(bool)));
573 connect(ui->buttonRename_RegExp, SIGNAL(clicked(bool)), this, SLOT(renameButtonClicked(bool)));
574 connect(ui->buttonRename_FileEx, SIGNAL(clicked(bool)), this, SLOT(renameButtonClicked(bool)));
575 connect(m_overwriteButtonGroup, SIGNAL(buttonClicked(int)), this, SLOT(overwriteModeChanged(int)));
576 connect(m_evenFilterCustumParamsHelp, SIGNAL(eventOccurred(QWidget*, QEvent*)), this, SLOT(customParamsHelpRequested(QWidget*, QEvent*)));
578 //--------------------------------
579 // Force initial GUI update
580 //--------------------------------
582 updateLameAlgoQuality(ui->sliderLameAlgoQuality->value());
583 updateMaximumInstances(ui->sliderMaxInstances->value());
584 toneAdjustTrebleChanged(ui->spinBoxToneAdjustTreble->value());
585 toneAdjustBassChanged(ui->spinBoxToneAdjustBass->value());
586 normalizationEnabledChanged(ui->checkBoxNormalizationFilterEnabled->isChecked());
587 customParamsChanged();
589 //--------------------------------
590 // Initialize actions
591 //--------------------------------
593 //Activate file menu actions
594 ui->actionOpenFolder->setData(QVariant::fromValue<bool>(false));
595 ui->actionOpenFolderRecursively->setData(QVariant::fromValue<bool>(true));
596 connect(ui->actionOpenFolder, SIGNAL(triggered()), this, SLOT(openFolderActionActivated()));
597 connect(ui->actionOpenFolderRecursively, SIGNAL(triggered()), this, SLOT(openFolderActionActivated()));
599 //Activate view menu actions
600 m_tabActionGroup = new QActionGroup(this);
601 m_tabActionGroup->addAction(ui->actionSourceFiles);
602 m_tabActionGroup->addAction(ui->actionOutputDirectory);
603 m_tabActionGroup->addAction(ui->actionCompression);
604 m_tabActionGroup->addAction(ui->actionMetaData);
605 m_tabActionGroup->addAction(ui->actionAdvancedOptions);
606 ui->actionSourceFiles->setData(0);
607 ui->actionOutputDirectory->setData(1);
608 ui->actionMetaData->setData(2);
609 ui->actionCompression->setData(3);
610 ui->actionAdvancedOptions->setData(4);
611 ui->actionSourceFiles->setChecked(true);
612 connect(m_tabActionGroup, SIGNAL(triggered(QAction*)), this, SLOT(tabActionActivated(QAction*)));
614 //Activate style menu actions
615 m_styleActionGroup = new QActionGroup(this);
616 m_styleActionGroup->addAction(ui->actionStylePlastique);
617 m_styleActionGroup->addAction(ui->actionStyleCleanlooks);
618 m_styleActionGroup->addAction(ui->actionStyleWindowsVista);
619 m_styleActionGroup->addAction(ui->actionStyleWindowsXP);
620 m_styleActionGroup->addAction(ui->actionStyleWindowsClassic);
621 ui->actionStylePlastique->setData(0);
622 ui->actionStyleCleanlooks->setData(1);
623 ui->actionStyleWindowsVista->setData(2);
624 ui->actionStyleWindowsXP->setData(3);
625 ui->actionStyleWindowsClassic->setData(4);
626 ui->actionStylePlastique->setChecked(true);
627 ui->actionStyleWindowsXP->setEnabled((QSysInfo::windowsVersion() & QSysInfo::WV_NT_based) >= QSysInfo::WV_XP && MUtils::GUI::themes_enabled());
628 ui->actionStyleWindowsVista->setEnabled((QSysInfo::windowsVersion() & QSysInfo::WV_NT_based) >= QSysInfo::WV_VISTA && MUtils::GUI::themes_enabled());
629 connect(m_styleActionGroup, SIGNAL(triggered(QAction*)), this, SLOT(styleActionActivated(QAction*)));
630 styleActionActivated(NULL);
632 //Populate the language menu
633 m_languageActionGroup = new QActionGroup(this);
634 QStringList translations;
635 if(MUtils::Translation::enumerate(translations) > 0)
637 for(QStringList::ConstIterator iter = translations.constBegin(); iter != translations.constEnd(); iter++)
639 QAction *currentLanguage = new QAction(this);
640 currentLanguage->setData(*iter);
641 currentLanguage->setText(MUtils::Translation::get_name(*iter));
642 currentLanguage->setIcon(QIcon(QString(":/flags/%1.png").arg(*iter)));
643 currentLanguage->setCheckable(true);
644 currentLanguage->setChecked(false);
645 m_languageActionGroup->addAction(currentLanguage);
646 ui->menuLanguage->insertAction(ui->actionLoadTranslationFromFile, currentLanguage);
649 ui->menuLanguage->insertSeparator(ui->actionLoadTranslationFromFile);
650 connect(ui->actionLoadTranslationFromFile, SIGNAL(triggered(bool)), this, SLOT(languageFromFileActionActivated(bool)));
651 connect(m_languageActionGroup, SIGNAL(triggered(QAction*)), this, SLOT(languageActionActivated(QAction*)));
652 ui->actionLoadTranslationFromFile->setChecked(false);
654 //Activate tools menu actions
655 ui->actionDisableUpdateReminder->setChecked(!m_settings->autoUpdateEnabled());
656 ui->actionDisableSounds->setChecked(!m_settings->soundsEnabled());
657 ui->actionDisableNeroAacNotifications->setChecked(!m_settings->neroAacNotificationsEnabled());
658 ui->actionDisableSlowStartupNotifications->setChecked(!m_settings->antivirNotificationsEnabled());
659 ui->actionDisableShellIntegration->setChecked(!m_settings->shellIntegrationEnabled());
660 ui->actionDisableShellIntegration->setDisabled(lamexp_version_portable() && ui->actionDisableShellIntegration->isChecked());
661 ui->actionCheckForBetaUpdates->setChecked(m_settings->autoUpdateCheckBeta() || lamexp_version_demo());
662 ui->actionCheckForBetaUpdates->setEnabled(!lamexp_version_demo());
663 ui->actionHibernateComputer->setChecked(m_settings->hibernateComputer());
664 ui->actionHibernateComputer->setEnabled(MUtils::OS::is_hibernation_supported());
665 connect(ui->actionDisableUpdateReminder, SIGNAL(triggered(bool)), this, SLOT(disableUpdateReminderActionTriggered(bool)));
666 connect(ui->actionDisableSounds, SIGNAL(triggered(bool)), this, SLOT(disableSoundsActionTriggered(bool)));
667 connect(ui->actionDisableNeroAacNotifications, SIGNAL(triggered(bool)), this, SLOT(disableNeroAacNotificationsActionTriggered(bool)));
668 connect(ui->actionDisableSlowStartupNotifications, SIGNAL(triggered(bool)), this, SLOT(disableSlowStartupNotificationsActionTriggered(bool)));
669 connect(ui->actionDisableShellIntegration, SIGNAL(triggered(bool)), this, SLOT(disableShellIntegrationActionTriggered(bool)));
670 connect(ui->actionShowDropBoxWidget, SIGNAL(triggered(bool)), this, SLOT(showDropBoxWidgetActionTriggered(bool)));
671 connect(ui->actionHibernateComputer, SIGNAL(triggered(bool)), this, SLOT(hibernateComputerActionTriggered(bool)));
672 connect(ui->actionCheckForBetaUpdates, SIGNAL(triggered(bool)), this, SLOT(checkForBetaUpdatesActionTriggered(bool)));
673 connect(ui->actionImportCueSheet, SIGNAL(triggered(bool)), this, SLOT(importCueSheetActionTriggered(bool)));
675 //Activate help menu actions
676 ui->actionVisitHomepage ->setData(QString::fromLatin1(lamexp_website_url()));
677 ui->actionVisitSupport ->setData(QString::fromLatin1(lamexp_support_url()));
678 ui->actionVisitMuldersSite ->setData(QString::fromLatin1(lamexp_mulders_url()));
679 ui->actionVisitTracker ->setData(QString::fromLatin1(lamexp_tracker_url()));
680 ui->actionVisitHAK ->setData(QString::fromLatin1(g_hydrogen_audio_url));
681 ui->actionDocumentManual ->setData(QString("%1/Manual.html") .arg(QApplication::applicationDirPath()));
682 ui->actionDocumentChangelog->setData(QString("%1/Changelog.html").arg(QApplication::applicationDirPath()));
683 ui->actionDocumentTranslate->setData(QString("%1/Translate.html").arg(QApplication::applicationDirPath()));
684 connect(ui->actionCheckUpdates, SIGNAL(triggered()), this, SLOT(checkUpdatesActionActivated()));
685 connect(ui->actionVisitSupport, SIGNAL(triggered()), this, SLOT(visitHomepageActionActivated()));
686 connect(ui->actionVisitTracker, SIGNAL(triggered()), this, SLOT(visitHomepageActionActivated()));
687 connect(ui->actionVisitHomepage, SIGNAL(triggered()), this, SLOT(visitHomepageActionActivated()));
688 connect(ui->actionVisitMuldersSite, SIGNAL(triggered()), this, SLOT(visitHomepageActionActivated()));
689 connect(ui->actionVisitHAK, SIGNAL(triggered()), this, SLOT(visitHomepageActionActivated()));
690 connect(ui->actionDocumentManual, SIGNAL(triggered()), this, SLOT(documentActionActivated()));
691 connect(ui->actionDocumentChangelog, SIGNAL(triggered()), this, SLOT(documentActionActivated()));
692 connect(ui->actionDocumentTranslate, SIGNAL(triggered()), this, SLOT(documentActionActivated()));
694 //--------------------------------
695 // Prepare to show window
696 //--------------------------------
698 //Center window in screen
699 QRect desktopRect = QApplication::desktop()->screenGeometry();
700 QRect thisRect = this->geometry();
701 move((desktopRect.width() - thisRect.width()) / 2, (desktopRect.height() - thisRect.height()) / 2);
702 setMinimumSize(thisRect.width(), thisRect.height());
704 //Create DropBox widget
705 m_dropBox = new DropBox(this, m_fileListModel, m_settings);
706 connect(m_fileListModel, SIGNAL(modelReset()), m_dropBox, SLOT(modelChanged()));
707 connect(m_fileListModel, SIGNAL(rowsInserted(QModelIndex,int,int)), m_dropBox, SLOT(modelChanged()));
708 connect(m_fileListModel, SIGNAL(rowsRemoved(QModelIndex,int,int)), m_dropBox, SLOT(modelChanged()));
709 connect(m_fileListModel, SIGNAL(rowAppended()), m_dropBox, SLOT(modelChanged()));
711 //Create message handler thread
712 m_messageHandler = new MessageHandlerThread(ipcChannel);
713 connect(m_messageHandler, SIGNAL(otherInstanceDetected()), this, SLOT(notifyOtherInstance()), Qt::QueuedConnection);
714 connect(m_messageHandler, SIGNAL(fileReceived(QString)), this, SLOT(addFileDelayed(QString)), Qt::QueuedConnection);
715 connect(m_messageHandler, SIGNAL(folderReceived(QString, bool)), this, SLOT(addFolderDelayed(QString, bool)), Qt::QueuedConnection);
716 connect(m_messageHandler, SIGNAL(killSignalReceived()), this, SLOT(close()), Qt::QueuedConnection);
717 m_messageHandler->start();
719 //Init delayed file handling
720 m_delayedFileList = new QStringList();
721 m_delayedFileTimer = new QTimer();
722 m_delayedFileTimer->setSingleShot(true);
723 m_delayedFileTimer->setInterval(5000);
724 connect(m_delayedFileTimer, SIGNAL(timeout()), this, SLOT(handleDelayedFiles()));
726 //Load translation
727 initializeTranslation();
729 //Re-translate (make sure we translate once)
730 QEvent languageChangeEvent(QEvent::LanguageChange);
731 changeEvent(&languageChangeEvent);
733 //Enable Drag & Drop
734 m_droppedFileList = new QList<QUrl>();
735 this->setAcceptDrops(true);
738 ////////////////////////////////////////////////////////////
739 // Destructor
740 ////////////////////////////////////////////////////////////
742 MainWindow::~MainWindow(void)
744 //Stop message handler thread
745 if(m_messageHandler && m_messageHandler->isRunning())
747 m_messageHandler->stop();
748 if(!m_messageHandler->wait(2500))
750 m_messageHandler->terminate();
751 m_messageHandler->wait();
755 //Unset models
756 SET_MODEL(ui->sourceFileView, NULL);
757 SET_MODEL(ui->outputFolderView, NULL);
758 SET_MODEL(ui->metaDataView, NULL);
760 //Free memory
761 MUTILS_DELETE(m_tabActionGroup);
762 MUTILS_DELETE(m_styleActionGroup);
763 MUTILS_DELETE(m_languageActionGroup);
764 MUTILS_DELETE(m_banner);
765 MUTILS_DELETE(m_fileSystemModel);
766 MUTILS_DELETE(m_messageHandler);
767 MUTILS_DELETE(m_droppedFileList);
768 MUTILS_DELETE(m_delayedFileList);
769 MUTILS_DELETE(m_delayedFileTimer);
770 MUTILS_DELETE(m_metaInfoModel);
771 MUTILS_DELETE(m_encoderButtonGroup);
772 MUTILS_DELETE(m_modeButtonGroup);
773 MUTILS_DELETE(m_overwriteButtonGroup);
774 MUTILS_DELETE(m_sourceFilesContextMenu);
775 MUTILS_DELETE(m_outputFolderFavoritesMenu);
776 MUTILS_DELETE(m_outputFolderContextMenu);
777 MUTILS_DELETE(m_dropBox);
778 MUTILS_DELETE(m_evenFilterCornerWidget);
779 MUTILS_DELETE(m_evenFilterCustumParamsHelp);
780 MUTILS_DELETE(m_evenFilterOutputFolderMouse);
781 MUTILS_DELETE(m_evenFilterOutputFolderView);
782 MUTILS_DELETE(m_evenFilterCompressionTab);
784 //Un-initialize the dialog
785 MUTILS_DELETE(ui);
788 ////////////////////////////////////////////////////////////
789 // PRIVATE FUNCTIONS
790 ////////////////////////////////////////////////////////////
793 * Add file to source list
795 void MainWindow::addFiles(const QStringList &files)
797 if(files.isEmpty())
799 return;
802 WITH_BLOCKED_SIGNALS(ui->tabWidget, setCurrentIndex, 0);
803 tabPageChanged(ui->tabWidget->currentIndex(), true);
805 INIT_BANNER();
806 FileAnalyzer *analyzer = new FileAnalyzer(files);
808 connect(analyzer, SIGNAL(fileSelected(QString)), m_banner, SLOT(setText(QString)), Qt::QueuedConnection);
809 connect(analyzer, SIGNAL(progressValChanged(unsigned int)), m_banner, SLOT(setProgressVal(unsigned int)), Qt::QueuedConnection);
810 connect(analyzer, SIGNAL(progressMaxChanged(unsigned int)), m_banner, SLOT(setProgressMax(unsigned int)), Qt::QueuedConnection);
811 connect(analyzer, SIGNAL(fileAnalyzed(AudioFileModel)), m_fileListModel, SLOT(addFile(AudioFileModel)), Qt::QueuedConnection);
812 connect(m_banner, SIGNAL(userAbort()), analyzer, SLOT(abortProcess()), Qt::DirectConnection);
816 m_fileListModel->setBlockUpdates(true);
817 QTime startTime = QTime::currentTime();
818 m_banner->show(tr("Adding file(s), please wait..."), analyzer);
820 catch(...)
822 /* ignore any exceptions that may occur */
825 m_fileListModel->setBlockUpdates(false);
826 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
827 ui->sourceFileView->update();
828 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
829 ui->sourceFileView->scrollToBottom();
830 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
832 if(analyzer->filesDenied())
834 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."))));
836 if(analyzer->filesDummyCDDA())
838 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>"))));
840 if(analyzer->filesCueSheet())
842 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."))));
844 if(analyzer->filesRejected())
846 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."))));
849 MUTILS_DELETE(analyzer);
850 m_banner->close();
854 * Add folder to source list
856 void MainWindow::addFolder(const QString &path, bool recursive, bool delayed)
858 QFileInfoList folderInfoList;
859 folderInfoList << QFileInfo(path);
860 QStringList fileList;
862 SHOW_BANNER(tr("Scanning folder(s) for files, please wait..."));
864 QApplication::processEvents();
865 MUtils::OS::check_key_state_esc();
867 while(!folderInfoList.isEmpty())
869 if(MUtils::OS::check_key_state_esc())
871 qWarning("Operation cancelled by user!");
872 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
873 fileList.clear();
874 break;
877 QDir currentDir(folderInfoList.takeFirst().canonicalFilePath());
878 QFileInfoList fileInfoList = currentDir.entryInfoList(QDir::Files | QDir::NoSymLinks);
880 while(!fileInfoList.isEmpty())
882 fileList << fileInfoList.takeFirst().canonicalFilePath();
885 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
887 if(recursive)
889 folderInfoList.append(currentDir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks));
890 QApplication::processEvents();
894 m_banner->close();
895 QApplication::processEvents();
897 if(!fileList.isEmpty())
899 if(delayed)
901 addFilesDelayed(fileList);
903 else
905 addFiles(fileList);
911 * Check for updates
913 bool MainWindow::checkForUpdates(void)
915 bool bReadyToInstall = false;
917 UpdateDialog *updateDialog = new UpdateDialog(m_settings, this);
918 updateDialog->exec();
920 if(updateDialog->getSuccess())
922 SHOW_CORNER_WIDGET(false);
923 m_settings->autoUpdateLastCheck(QDate::currentDate().toString(Qt::ISODate));
924 bReadyToInstall = updateDialog->updateReadyToInstall();
927 MUTILS_DELETE(updateDialog);
928 return bReadyToInstall;
932 * Refresh list of favorites
934 void MainWindow::refreshFavorites(void)
936 QList<QAction*> folderList = m_outputFolderFavoritesMenu->actions();
937 QStringList favorites = m_settings->favoriteOutputFolders().split("|", QString::SkipEmptyParts);
938 while(favorites.count() > 6) favorites.removeFirst();
940 while(!folderList.isEmpty())
942 QAction *currentItem = folderList.takeFirst();
943 if(currentItem->isSeparator()) break;
944 m_outputFolderFavoritesMenu->removeAction(currentItem);
945 MUTILS_DELETE(currentItem);
948 QAction *lastItem = m_outputFolderFavoritesMenu->actions().first();
950 while(!favorites.isEmpty())
952 QString path = favorites.takeLast();
953 if(QDir(path).exists())
955 QAction *action = new QAction(QIcon(":/icons/folder_go.png"), QDir::toNativeSeparators(path), this);
956 action->setData(path);
957 m_outputFolderFavoritesMenu->insertAction(lastItem, action);
958 connect(action, SIGNAL(triggered(bool)), this, SLOT(gotoFavoriteFolder()));
959 lastItem = action;
965 * Initilaize translation
967 void MainWindow::initializeTranslation(void)
969 bool translationLoaded = false;
971 //Try to load "external" translation file
972 if(!m_settings->currentLanguageFile().isEmpty())
974 const QString qmFilePath = QFileInfo(m_settings->currentLanguageFile()).canonicalFilePath();
975 if((!qmFilePath.isEmpty()) && QFileInfo(qmFilePath).exists() && QFileInfo(qmFilePath).isFile() && (QFileInfo(qmFilePath).suffix().compare("qm", Qt::CaseInsensitive) == 0))
977 if(MUtils::Translation::install_translator_from_file(qmFilePath))
979 QList<QAction*> actions = m_languageActionGroup->actions();
980 while(!actions.isEmpty()) actions.takeFirst()->setChecked(false);
981 ui->actionLoadTranslationFromFile->setChecked(true);
982 translationLoaded = true;
987 //Try to load "built-in" translation file
988 if(!translationLoaded)
990 QList<QAction*> languageActions = m_languageActionGroup->actions();
991 while(!languageActions.isEmpty())
993 QAction *currentLanguage = languageActions.takeFirst();
994 if(currentLanguage->data().toString().compare(m_settings->currentLanguage(), Qt::CaseInsensitive) == 0)
996 currentLanguage->setChecked(true);
997 languageActionActivated(currentLanguage);
998 translationLoaded = true;
1003 //Fallback to default translation
1004 if(!translationLoaded)
1006 QList<QAction*> languageActions = m_languageActionGroup->actions();
1007 while(!languageActions.isEmpty())
1009 QAction *currentLanguage = languageActions.takeFirst();
1010 if(currentLanguage->data().toString().compare(MUtils::Translation::DEFAULT_LANGID, Qt::CaseInsensitive) == 0)
1012 currentLanguage->setChecked(true);
1013 languageActionActivated(currentLanguage);
1014 translationLoaded = true;
1019 //Make sure we loaded some translation
1020 if(!translationLoaded)
1022 qFatal("Failed to load any translation, this is NOT supposed to happen!");
1027 * Open a document link
1029 void MainWindow::openDocumentLink(QAction *const action)
1031 if(!(action->data().isValid() && (action->data().type() == QVariant::String)))
1033 qWarning("Cannot open document for this QAction!");
1034 return;
1037 //Try to open exitsing document file
1038 const QFileInfo document(action->data().toString());
1039 if(document.exists() && document.isFile() && (document.size() >= 1024))
1041 QDesktopServices::openUrl(QUrl::fromLocalFile(document.canonicalFilePath()));
1042 return;
1045 //Document not found -> fallback mode!
1046 qWarning("Document '%s' not found -> redirecting to the website!", MUTILS_UTF8(document.fileName()));
1047 const QUrl url(QString("%1/%2").arg(QString::fromLatin1(g_documents_base_url), document.fileName()));
1048 QDesktopServices::openUrl(url);
1051 ////////////////////////////////////////////////////////////
1052 // EVENTS
1053 ////////////////////////////////////////////////////////////
1056 * Window is about to be shown
1058 void MainWindow::showEvent(QShowEvent *event)
1060 m_accepted = false;
1061 resizeEvent(NULL);
1062 sourceModelChanged();
1064 if(!event->spontaneous())
1066 WITH_BLOCKED_SIGNALS(ui->tabWidget, setCurrentIndex, 0);
1067 tabPageChanged(ui->tabWidget->currentIndex(), true);
1070 if(m_firstTimeShown)
1072 m_firstTimeShown = false;
1073 QTimer::singleShot(0, this, SLOT(windowShown()));
1075 else
1077 if(m_settings->dropBoxWidgetEnabled())
1079 m_dropBox->setVisible(true);
1085 * Re-translate the UI
1087 void MainWindow::changeEvent(QEvent *e)
1089 QMainWindow::changeEvent(e);
1090 if(e->type() != QEvent::LanguageChange)
1092 return;
1095 int comboBoxIndex[6];
1097 //Backup combobox indices, as retranslateUi() resets
1098 comboBoxIndex[0] = ui->comboBoxMP3ChannelMode->currentIndex();
1099 comboBoxIndex[1] = ui->comboBoxSamplingRate->currentIndex();
1100 comboBoxIndex[2] = ui->comboBoxAACProfile->currentIndex();
1101 comboBoxIndex[3] = ui->comboBoxAftenCodingMode->currentIndex();
1102 comboBoxIndex[4] = ui->comboBoxAftenDRCMode->currentIndex();
1103 comboBoxIndex[5] = ui->comboBoxOpusFramesize->currentIndex();
1105 //Re-translate from UIC
1106 ui->retranslateUi(this);
1108 //Restore combobox indices
1109 ui->comboBoxMP3ChannelMode->setCurrentIndex(comboBoxIndex[0]);
1110 ui->comboBoxSamplingRate->setCurrentIndex(comboBoxIndex[1]);
1111 ui->comboBoxAACProfile->setCurrentIndex(comboBoxIndex[2]);
1112 ui->comboBoxAftenCodingMode->setCurrentIndex(comboBoxIndex[3]);
1113 ui->comboBoxAftenDRCMode->setCurrentIndex(comboBoxIndex[4]);
1114 ui->comboBoxOpusFramesize->setCurrentIndex(comboBoxIndex[5]);
1116 //Update the window title
1117 if(MUTILS_DEBUG)
1119 setWindowTitle(QString("%1 [!!! DEBUG BUILD !!!]").arg(windowTitle()));
1121 else if(lamexp_version_demo())
1123 setWindowTitle(QString("%1 [%2]").arg(windowTitle(), tr("DEMO VERSION")));
1126 //Manually re-translate widgets that UIC doesn't handle
1127 m_outputFolderNoteBox->setText(tr("Initializing directory outline, please be patient..."));
1128 m_dropNoteLabel->setText(QString("<br><img src=\":/images/DropZone.png\"><br><br>%1").arg(tr("You can drop in audio files here!")));
1129 if(QLabel *cornerWidget = dynamic_cast<QLabel*>(ui->menubar->cornerWidget()))
1131 cornerWidget->setText(QString("<nobr><img src=\":/icons/exclamation_small.png\">&nbsp;<b style=\"color:darkred\">%1</b>&nbsp;&nbsp;&nbsp;</nobr>").arg(tr("Check for Updates")));
1133 m_showDetailsContextAction->setText(tr("Show Details"));
1134 m_previewContextAction->setText(tr("Open File in External Application"));
1135 m_findFileContextAction->setText(tr("Browse File Location"));
1136 m_showFolderContextAction->setText(tr("Browse Selected Folder"));
1137 m_refreshFolderContextAction->setText(tr("Refresh Directory Outline"));
1138 m_goUpFolderContextAction->setText(tr("Go To Parent Directory"));
1139 m_addFavoriteFolderAction->setText(tr("Bookmark Current Output Folder"));
1140 m_exportCsvContextAction->setText(tr("Export Meta Tags to CSV File"));
1141 m_importCsvContextAction->setText(tr("Import Meta Tags from CSV File"));
1143 //Force GUI update
1144 m_metaInfoModel->clearData();
1145 m_metaInfoModel->setData(m_metaInfoModel->index(4, 1), m_settings->metaInfoPosition());
1146 updateEncoder(m_settings->compressionEncoder());
1147 updateLameAlgoQuality(ui->sliderLameAlgoQuality->value());
1148 updateMaximumInstances(ui->sliderMaxInstances->value());
1149 renameOutputPatternChanged(ui->lineEditRenamePattern->text(), true);
1150 renameRegExpSearchChanged (ui->lineEditRenameRegExp_Search ->text(), true);
1151 renameRegExpReplaceChanged(ui->lineEditRenameRegExp_Replace->text(), true);
1153 //Re-install shell integration
1154 if(m_settings->shellIntegrationEnabled())
1156 ShellIntegration::install();
1159 //Translate system menu
1160 MUtils::GUI::sysmenu_update(this, IDM_ABOUTBOX, ui->buttonAbout->text());
1162 //Force resize event
1163 QApplication::postEvent(this, new QResizeEvent(this->size(), QSize()));
1164 for(QObjectList::ConstIterator iter = this->children().constBegin(); iter != this->children().constEnd(); iter++)
1166 if(QWidget *child = dynamic_cast<QWidget*>(*iter))
1168 QApplication::postEvent(child, new QResizeEvent(child->size(), QSize()));
1172 //Force tabe page change
1173 tabPageChanged(ui->tabWidget->currentIndex(), true);
1177 * File dragged over window
1179 void MainWindow::dragEnterEvent(QDragEnterEvent *event)
1181 QStringList formats = event->mimeData()->formats();
1183 if(formats.contains("application/x-qt-windows-mime;value=\"FileNameW\"", Qt::CaseInsensitive) && formats.contains("text/uri-list", Qt::CaseInsensitive))
1185 event->acceptProposedAction();
1190 * File dropped onto window
1192 void MainWindow::dropEvent(QDropEvent *event)
1194 m_droppedFileList->clear();
1195 (*m_droppedFileList) << event->mimeData()->urls();
1196 if(!m_droppedFileList->isEmpty())
1198 PLAY_SOUND_OPTIONAL("drop", true);
1199 QTimer::singleShot(0, this, SLOT(handleDroppedFiles()));
1204 * Window tries to close
1206 void MainWindow::closeEvent(QCloseEvent *event)
1208 if(BANNER_VISIBLE || m_delayedFileTimer->isActive())
1210 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN);
1211 event->ignore();
1214 if(m_dropBox)
1216 m_dropBox->hide();
1221 * Window was resized
1223 void MainWindow::resizeEvent(QResizeEvent *event)
1225 if(event) QMainWindow::resizeEvent(event);
1227 if(QWidget *port = ui->sourceFileView->viewport())
1229 m_dropNoteLabel->setGeometry(port->geometry());
1232 if(QWidget *port = ui->outputFolderView->viewport())
1234 m_outputFolderNoteBox->setGeometry(16, (port->height() - 64) / 2, port->width() - 32, 64);
1239 * Key press event filter
1241 void MainWindow::keyPressEvent(QKeyEvent *e)
1243 if(e->key() == Qt::Key_Delete)
1245 if(ui->sourceFileView->isVisible())
1247 QTimer::singleShot(0, this, SLOT(removeFileButtonClicked()));
1248 return;
1252 if(e->modifiers().testFlag(Qt::ControlModifier) && (e->key() == Qt::Key_F5))
1254 initializeTranslation();
1255 MUtils::Sound::beep(MUtils::Sound::BEEP_NFO);
1256 return;
1259 if(e->key() == Qt::Key_F5)
1261 if(ui->outputFolderView->isVisible())
1263 QTimer::singleShot(0, this, SLOT(refreshFolderContextActionTriggered()));
1264 return;
1268 QMainWindow::keyPressEvent(e);
1272 * Event filter
1274 bool MainWindow::eventFilter(QObject *obj, QEvent *event)
1276 if(obj == m_fileSystemModel)
1278 if(QApplication::overrideCursor() == NULL)
1280 QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
1281 QTimer::singleShot(250, this, SLOT(restoreCursor()));
1285 return QMainWindow::eventFilter(obj, event);
1288 bool MainWindow::event(QEvent *e)
1290 switch(e->type())
1292 case MUtils::GUI::USER_EVENT_QUERYENDSESSION:
1293 qWarning("System is shutting down, main window prepares to close...");
1294 if(BANNER_VISIBLE) m_banner->close();
1295 if(m_delayedFileTimer->isActive()) m_delayedFileTimer->stop();
1296 return true;
1297 case MUtils::GUI::USER_EVENT_ENDSESSION:
1298 qWarning("System is shutting down, main window will close now...");
1299 if(isVisible())
1301 while(!close())
1303 QApplication::processEvents(QEventLoop::WaitForMoreEvents & QEventLoop::ExcludeUserInputEvents);
1306 m_fileListModel->clearFiles();
1307 return true;
1308 case QEvent::MouseButtonPress:
1309 if(ui->outputFolderEdit->isVisible())
1311 QTimer::singleShot(0, this, SLOT(outputFolderEditFinished()));
1313 default:
1314 return QMainWindow::event(e);
1318 bool MainWindow::winEvent(MSG *message, long *result)
1320 if(MUtils::GUI::sysmenu_check_msg(message, IDM_ABOUTBOX))
1322 QTimer::singleShot(0, ui->buttonAbout, SLOT(click()));
1323 *result = 0;
1324 return true;
1326 return false;
1329 ////////////////////////////////////////////////////////////
1330 // Slots
1331 ////////////////////////////////////////////////////////////
1333 // =========================================================
1334 // Show window slots
1335 // =========================================================
1338 * Window shown
1340 void MainWindow::windowShown(void)
1342 const MUtils::OS::ArgumentMap &arguments = MUtils::OS::arguments(); //QApplication::arguments();
1344 //Force resize event
1345 resizeEvent(NULL);
1347 //First run?
1348 const bool firstRun = arguments.contains("first-run");
1350 //Check license
1351 if((m_settings->licenseAccepted() <= 0) || firstRun)
1353 int iAccepted = m_settings->licenseAccepted();
1355 if((iAccepted == 0) || firstRun)
1357 AboutDialog *about = new AboutDialog(m_settings, this, true);
1358 iAccepted = about->exec();
1359 if(iAccepted <= 0) iAccepted = -2;
1360 MUTILS_DELETE(about);
1363 if(iAccepted <= 0)
1365 m_settings->licenseAccepted(++iAccepted);
1366 m_settings->syncNow();
1367 QApplication::processEvents();
1368 MUtils::Sound::play_sound("whammy", false);
1369 QMessageBox::critical(this, tr("License Declined"), tr("You have declined the license. Consequently the application will exit now!"), tr("Goodbye!"));
1370 QFileInfo uninstallerInfo = QFileInfo(QString("%1/Uninstall.exe").arg(QApplication::applicationDirPath()));
1371 if(uninstallerInfo.exists())
1373 QString uninstallerDir = uninstallerInfo.canonicalPath();
1374 QString uninstallerPath = uninstallerInfo.canonicalFilePath();
1375 for(int i = 0; i < 3; i++)
1377 if(MUtils::OS::shell_open(this, QDir::toNativeSeparators(uninstallerPath), "/Force", QDir::toNativeSeparators(uninstallerDir))) break;
1380 QApplication::quit();
1381 return;
1384 MUtils::Sound::play_sound("woohoo", false);
1385 m_settings->licenseAccepted(1);
1386 m_settings->syncNow();
1387 if(lamexp_version_demo()) showAnnounceBox();
1390 //Check for expiration
1391 if(lamexp_version_demo())
1393 if(MUtils::OS::current_date() >= lamexp_version_expires())
1395 qWarning("Binary has expired !!!");
1396 MUtils::Sound::play_sound("whammy", false);
1397 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)
1399 checkForUpdates();
1401 QApplication::quit();
1402 return;
1406 //Slow startup indicator
1407 if(m_settings->slowStartup() && m_settings->antivirNotificationsEnabled())
1409 QString message;
1410 message += NOBR(tr("It seems that a bogus anti-virus software is slowing down the startup of LameXP.")).append("<br>");
1411 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>");
1412 if(QMessageBox::warning(this, tr("Slow Startup"), message, tr("Discard"), tr("Don't Show Again")) == 1)
1414 m_settings->antivirNotificationsEnabled(false);
1415 ui->actionDisableSlowStartupNotifications->setChecked(!m_settings->antivirNotificationsEnabled());
1419 //Update reminder
1420 if(MUtils::OS::current_date() >= MUtils::Version::app_build_date().addYears(1))
1422 qWarning("Binary is more than a year old, time to update!");
1423 SHOW_CORNER_WIDGET(true);
1424 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"));
1425 switch(ret)
1427 case 0:
1428 if(checkForUpdates())
1430 QApplication::quit();
1431 return;
1433 break;
1434 case 1:
1435 QApplication::quit();
1436 return;
1437 default:
1438 QEventLoop loop; QTimer::singleShot(7000, &loop, SLOT(quit()));
1439 MUtils::Sound::play_sound("waiting", true);
1440 SHOW_BANNER_ARG(tr("Skipping update check this time, please be patient..."), &loop);
1441 break;
1444 else
1446 QDate lastUpdateCheck = QDate::fromString(m_settings->autoUpdateLastCheck(), Qt::ISODate);
1447 if((!firstRun) && ((!lastUpdateCheck.isValid()) || (MUtils::OS::current_date() >= lastUpdateCheck.addDays(14))))
1449 SHOW_CORNER_WIDGET(true);
1450 if(m_settings->autoUpdateEnabled())
1452 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)
1454 if(checkForUpdates())
1456 QApplication::quit();
1457 return;
1464 //Check for AAC support
1465 const int aacEncoder = EncoderRegistry::getAacEncoder();
1466 if(aacEncoder == SettingsModel::AAC_ENCODER_NERO)
1468 if(m_settings->neroAacNotificationsEnabled())
1470 if(lamexp_tools_version("neroAacEnc.exe") < lamexp_toolver_neroaac())
1472 QString messageText;
1473 messageText += NOBR(tr("LameXP detected that your version of the Nero AAC encoder is outdated!")).append("<br>");
1474 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>");
1475 messageText += NOBR(tr("You can download the latest version of the Nero AAC encoder from the Nero website at:")).append("<br>");
1476 messageText += "<nobr><tt>" + LINK(AboutDialog::neroAacUrl) + "</tt></nobr><br><br>";
1477 messageText += NOBR(tr("(Hint: Please ignore the name of the downloaded ZIP file and check the included 'changelog.txt' instead!)")).append("<br>");
1478 QMessageBox::information(this, tr("AAC Encoder Outdated"), messageText);
1482 else
1484 if(m_settings->neroAacNotificationsEnabled() && (aacEncoder <= SettingsModel::AAC_ENCODER_NONE))
1486 QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
1487 if(appPath.isEmpty()) appPath = QCoreApplication::applicationDirPath();
1488 QString messageText;
1489 messageText += NOBR(tr("The Nero AAC encoder could not be found. AAC encoding support will be disabled.")).append("<br>");
1490 messageText += NOBR(tr("Please put 'neroAacEnc.exe', 'neroAacDec.exe' and 'neroAacTag.exe' into the LameXP directory!")).append("<br><br>");
1491 messageText += NOBR(tr("Your LameXP directory is located here:")).append("<br>");
1492 messageText += QString("<nobr><tt>%1</tt></nobr><br><br>").arg(FSLINK(QDir::toNativeSeparators(appPath)));
1493 messageText += NOBR(tr("You can download the Nero AAC encoder for free from the official Nero website at:")).append("<br>");
1494 messageText += "<nobr><tt>" + LINK(AboutDialog::neroAacUrl) + "</tt></nobr><br>";
1495 if(QMessageBox::information(this, tr("AAC Support Disabled"), messageText, tr("Discard"), tr("Don't Show Again")) == 1)
1497 m_settings->neroAacNotificationsEnabled(false);
1498 ui->actionDisableNeroAacNotifications->setChecked(!m_settings->neroAacNotificationsEnabled());
1503 //Add files from the command-line
1504 QStringList addedFiles;
1505 foreach(const QString &value, arguments.values("add"))
1507 if(!value.isEmpty())
1509 QFileInfo currentFile(value);
1510 qDebug("Adding file from CLI: %s", MUTILS_UTF8(currentFile.absoluteFilePath()));
1511 addedFiles.append(currentFile.absoluteFilePath());
1514 if(!addedFiles.isEmpty())
1516 addFilesDelayed(addedFiles);
1519 //Add folders from the command-line
1520 foreach(const QString &value, arguments.values("add-folder"))
1522 if(!value.isEmpty())
1524 const QFileInfo currentFile(value);
1525 qDebug("Adding folder from CLI: %s", MUTILS_UTF8(currentFile.absoluteFilePath()));
1526 addFolder(currentFile.absoluteFilePath(), false, true);
1529 foreach(const QString &value, arguments.values("add-recursive"))
1531 if(!value.isEmpty())
1533 const QFileInfo currentFile(value);
1534 qDebug("Adding folder recursively from CLI: %s", MUTILS_UTF8(currentFile.absoluteFilePath()));
1535 addFolder(currentFile.absoluteFilePath(), true, true);
1539 //Enable shell integration
1540 if(m_settings->shellIntegrationEnabled())
1542 ShellIntegration::install();
1545 //Make DropBox visible
1546 if(m_settings->dropBoxWidgetEnabled())
1548 m_dropBox->setVisible(true);
1553 * Show announce box
1555 void MainWindow::showAnnounceBox(void)
1557 const unsigned int timeout = 8U;
1559 const QString announceText = QString("%1<br><br>%2<br><nobr><tt>%3</tt></nobr><br>").arg
1561 NOBR("We are still looking for LameXP translators!"),
1562 NOBR("If you are willing to translate LameXP to your language or to complete an existing translation, please refer to:"),
1563 LINK("http://lamexp.sourceforge.net/doc/Translate.html")
1566 QMessageBox *announceBox = new QMessageBox(QMessageBox::Warning, "We want you!", announceText, QMessageBox::NoButton, this);
1567 announceBox->setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
1568 announceBox->setIconPixmap(QIcon(":/images/Announcement.png").pixmap(64,79));
1570 QTimer *timers[timeout+1];
1571 QPushButton *buttons[timeout+1];
1573 for(unsigned int i = 0; i <= timeout; i++)
1575 QString text = (i > 0) ? QString("%1 (%2)").arg(tr("Discard"), QString::number(i)) : tr("Discard");
1576 buttons[i] = announceBox->addButton(text, (i > 0) ? QMessageBox::NoRole : QMessageBox::AcceptRole);
1579 for(unsigned int i = 0; i <= timeout; i++)
1581 buttons[i]->setEnabled(i == 0);
1582 buttons[i]->setVisible(i == timeout);
1585 for(unsigned int i = 0; i < timeout; i++)
1587 timers[i] = new QTimer(this);
1588 timers[i]->setSingleShot(true);
1589 timers[i]->setInterval(1000);
1590 connect(timers[i], SIGNAL(timeout()), buttons[i+1], SLOT(hide()));
1591 connect(timers[i], SIGNAL(timeout()), buttons[i], SLOT(show()));
1592 if(i > 0)
1594 connect(timers[i], SIGNAL(timeout()), timers[i-1], SLOT(start()));
1598 timers[timeout-1]->start();
1599 announceBox->exec();
1601 for(unsigned int i = 0; i < timeout; i++)
1603 timers[i]->stop();
1604 MUTILS_DELETE(timers[i]);
1607 MUTILS_DELETE(announceBox);
1610 // =========================================================
1611 // Main button solots
1612 // =========================================================
1615 * Encode button
1617 void MainWindow::encodeButtonClicked(void)
1619 static const unsigned __int64 oneGigabyte = 1073741824ui64;
1620 static const unsigned __int64 minimumFreeDiskspaceMultiplier = 2ui64;
1621 static const char *writeTestBuffer = "LAMEXP_WRITE_TEST";
1623 ABORT_IF_BUSY;
1625 if(m_fileListModel->rowCount() < 1)
1627 QMessageBox::warning(this, tr("LameXP"), NOBR(tr("You must add at least one file to the list before proceeding!")));
1628 ui->tabWidget->setCurrentIndex(0);
1629 return;
1632 QString tempFolder = m_settings->customTempPathEnabled() ? m_settings->customTempPath() : MUtils::temp_folder();
1633 if(!QFileInfo(tempFolder).exists() || !QFileInfo(tempFolder).isDir())
1635 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)
1637 SET_CHECKBOX_STATE(ui->checkBoxUseSystemTempFolder, (!m_settings->customTempPathEnabledDefault()));
1639 return;
1642 quint64 currentFreeDiskspace = 0;
1643 if(MUtils::OS::free_diskspace(tempFolder, currentFreeDiskspace))
1645 if(currentFreeDiskspace < (oneGigabyte * minimumFreeDiskspaceMultiplier))
1647 QStringList tempFolderParts = tempFolder.split("/", QString::SkipEmptyParts, Qt::CaseInsensitive);
1648 tempFolderParts.takeLast();
1649 PLAY_SOUND_OPTIONAL("whammy", false);
1650 QString lowDiskspaceMsg = QString("%1<br>%2<br><br>%3<br>%4<br>").arg
1652 NOBR(tr("There are less than %1 GB of free diskspace available on your system's TEMP folder.").arg(QString::number(minimumFreeDiskspaceMultiplier))),
1653 NOBR(tr("It is highly recommend to free up more diskspace before proceeding with the encode!")),
1654 NOBR(tr("Your TEMP folder is located at:")),
1655 QString("<nobr><tt>%1</tt></nobr>").arg(FSLINK(tempFolderParts.join("\\")))
1657 switch(QMessageBox::warning(this, tr("Low Diskspace Warning"), lowDiskspaceMsg, tr("Abort Encoding Process"), tr("Clean Disk Now"), tr("Ignore")))
1659 case 1:
1660 QProcess::startDetached(QString("%1/cleanmgr.exe").arg(MUtils::OS::known_folder(MUtils::OS::FOLDER_SYSTEMFOLDER)), QStringList() << "/D" << tempFolderParts.first());
1661 case 0:
1662 return;
1663 break;
1664 default:
1665 QMessageBox::warning(this, tr("Low Diskspace"), NOBR(tr("You are proceeding with low diskspace. Problems might occur!")));
1666 break;
1671 switch(m_settings->compressionEncoder())
1673 case SettingsModel::MP3Encoder:
1674 case SettingsModel::VorbisEncoder:
1675 case SettingsModel::AACEncoder:
1676 case SettingsModel::AC3Encoder:
1677 case SettingsModel::FLACEncoder:
1678 case SettingsModel::OpusEncoder:
1679 case SettingsModel::DCAEncoder:
1680 case SettingsModel::MACEncoder:
1681 case SettingsModel::PCMEncoder:
1682 break;
1683 default:
1684 QMessageBox::warning(this, tr("LameXP"), tr("Sorry, an unsupported encoder has been chosen!"));
1685 ui->tabWidget->setCurrentIndex(3);
1686 return;
1689 if(!m_settings->outputToSourceDir())
1691 QFile writeTest(QString("%1/~%2.txt").arg(m_settings->outputDir(), MUtils::rand_str()));
1692 if(!(writeTest.open(QIODevice::ReadWrite) && (writeTest.write(writeTestBuffer) == strlen(writeTestBuffer))))
1694 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!")));
1695 ui->tabWidget->setCurrentIndex(1);
1696 return;
1698 else
1700 writeTest.close();
1701 writeTest.remove();
1705 m_accepted = true;
1706 close();
1710 * About button
1712 void MainWindow::aboutButtonClicked(void)
1714 ABORT_IF_BUSY;
1716 TEMP_HIDE_DROPBOX
1718 AboutDialog *aboutBox = new AboutDialog(m_settings, this);
1719 aboutBox->exec();
1720 MUTILS_DELETE(aboutBox);
1725 * Close button
1727 void MainWindow::closeButtonClicked(void)
1729 ABORT_IF_BUSY;
1730 close();
1733 // =========================================================
1734 // Tab widget slots
1735 // =========================================================
1738 * Tab page changed
1740 void MainWindow::tabPageChanged(int idx, const bool silent)
1742 resizeEvent(NULL);
1744 //Update "view" menu
1745 QList<QAction*> actions = m_tabActionGroup->actions();
1746 for(int i = 0; i < actions.count(); i++)
1748 bool ok = false;
1749 int actionIndex = actions.at(i)->data().toInt(&ok);
1750 if(ok && actionIndex == idx)
1752 actions.at(i)->setChecked(true);
1756 //Play tick sound
1757 if(!silent)
1759 PLAY_SOUND_OPTIONAL("tick", true);
1762 int initialWidth = this->width();
1763 int maximumWidth = QApplication::desktop()->availableGeometry().width();
1765 //Make sure all tab headers are fully visible
1766 if(this->isVisible())
1768 int delta = ui->tabWidget->sizeHint().width() - ui->tabWidget->width();
1769 if(delta > 0)
1771 this->resize(qMin(this->width() + delta, maximumWidth), this->height());
1775 //Tab specific operations
1776 if(idx == ui->tabWidget->indexOf(ui->tabOptions) && ui->scrollArea->widget() && this->isVisible())
1778 ui->scrollArea->widget()->updateGeometry();
1779 ui->scrollArea->viewport()->updateGeometry();
1780 qApp->processEvents();
1781 int delta = ui->scrollArea->widget()->width() - ui->scrollArea->viewport()->width();
1782 if(delta > 0)
1784 this->resize(qMin(this->width() + delta, maximumWidth), this->height());
1787 else if(idx == ui->tabWidget->indexOf(ui->tabSourceFiles))
1789 m_dropNoteLabel->setGeometry(0, 0, ui->sourceFileView->width(), ui->sourceFileView->height());
1791 else if(idx == ui->tabWidget->indexOf(ui->tabOutputDir))
1793 if(!m_fileSystemModel)
1795 QTimer::singleShot(125, this, SLOT(initOutputFolderModel()));
1797 else
1799 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
1803 //Center window around previous position
1804 if(initialWidth < this->width())
1806 QPoint prevPos = this->pos();
1807 int delta = (this->width() - initialWidth) >> 2;
1808 move(prevPos.x() - delta, prevPos.y());
1813 * Tab action triggered
1815 void MainWindow::tabActionActivated(QAction *action)
1817 if(action && action->data().isValid())
1819 bool ok = false;
1820 int index = action->data().toInt(&ok);
1821 if(ok)
1823 ui->tabWidget->setCurrentIndex(index);
1828 // =========================================================
1829 // Menubar slots
1830 // =========================================================
1833 * Handle corner widget Event
1835 void MainWindow::cornerWidgetEventOccurred(QWidget *sender, QEvent *event)
1837 if(event->type() == QEvent::MouseButtonPress)
1839 QTimer::singleShot(0, this, SLOT(checkUpdatesActionActivated()));
1843 // =========================================================
1844 // View menu slots
1845 // =========================================================
1848 * Style action triggered
1850 void MainWindow::styleActionActivated(QAction *action)
1852 //Change style setting
1853 if(action && action->data().isValid())
1855 bool ok = false;
1856 int actionIndex = action->data().toInt(&ok);
1857 if(ok)
1859 m_settings->interfaceStyle(actionIndex);
1863 //Set up the new style
1864 switch(m_settings->interfaceStyle())
1866 case 1:
1867 if(ui->actionStyleCleanlooks->isEnabled())
1869 ui->actionStyleCleanlooks->setChecked(true);
1870 QApplication::setStyle(new QCleanlooksStyle());
1871 break;
1873 case 2:
1874 if(ui->actionStyleWindowsVista->isEnabled())
1876 ui->actionStyleWindowsVista->setChecked(true);
1877 QApplication::setStyle(new QWindowsVistaStyle());
1878 break;
1880 case 3:
1881 if(ui->actionStyleWindowsXP->isEnabled())
1883 ui->actionStyleWindowsXP->setChecked(true);
1884 QApplication::setStyle(new QWindowsXPStyle());
1885 break;
1887 case 4:
1888 if(ui->actionStyleWindowsClassic->isEnabled())
1890 ui->actionStyleWindowsClassic->setChecked(true);
1891 QApplication::setStyle(new QWindowsStyle());
1892 break;
1894 default:
1895 ui->actionStylePlastique->setChecked(true);
1896 QApplication::setStyle(new QPlastiqueStyle());
1897 break;
1900 //Force re-translate after style change
1901 if(QEvent *e = new QEvent(QEvent::LanguageChange))
1903 changeEvent(e);
1904 MUTILS_DELETE(e);
1907 //Make transparent
1908 const type_info &styleType = typeid(*qApp->style());
1909 const bool bTransparent = ((typeid(QWindowsVistaStyle) == styleType) || (typeid(QWindowsXPStyle) == styleType));
1910 MAKE_TRANSPARENT(ui->scrollArea, bTransparent);
1912 //Also force a re-size event
1913 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
1914 resizeEvent(NULL);
1918 * Language action triggered
1920 void MainWindow::languageActionActivated(QAction *action)
1922 if(action->data().type() == QVariant::String)
1924 QString langId = action->data().toString();
1926 if(MUtils::Translation::install_translator(langId))
1928 action->setChecked(true);
1929 ui->actionLoadTranslationFromFile->setChecked(false);
1930 m_settings->currentLanguage(langId);
1931 m_settings->currentLanguageFile(QString());
1937 * Load language from file action triggered
1939 void MainWindow::languageFromFileActionActivated(bool checked)
1941 QFileDialog dialog(this, tr("Load Translation"));
1942 dialog.setFileMode(QFileDialog::ExistingFile);
1943 dialog.setNameFilter(QString("%1 (*.qm)").arg(tr("Translation Files")));
1945 if(dialog.exec())
1947 QStringList selectedFiles = dialog.selectedFiles();
1948 const QString qmFile = QFileInfo(selectedFiles.first()).canonicalFilePath();
1949 if(MUtils::Translation::install_translator_from_file(qmFile))
1951 QList<QAction*> actions = m_languageActionGroup->actions();
1952 while(!actions.isEmpty())
1954 actions.takeFirst()->setChecked(false);
1956 ui->actionLoadTranslationFromFile->setChecked(true);
1957 m_settings->currentLanguageFile(qmFile);
1959 else
1961 languageActionActivated(m_languageActionGroup->actions().first());
1966 // =========================================================
1967 // Tools menu slots
1968 // =========================================================
1971 * Disable update reminder action
1973 void MainWindow::disableUpdateReminderActionTriggered(bool checked)
1975 if(checked)
1977 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))
1979 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!"))));
1980 m_settings->autoUpdateEnabled(false);
1982 else
1984 m_settings->autoUpdateEnabled(true);
1987 else
1989 QMessageBox::information(this, tr("Update Reminder"), NOBR(tr("The update reminder has been re-enabled.")));
1990 m_settings->autoUpdateEnabled(true);
1993 ui->actionDisableUpdateReminder->setChecked(!m_settings->autoUpdateEnabled());
1997 * Disable sound effects action
1999 void MainWindow::disableSoundsActionTriggered(bool checked)
2001 if(checked)
2003 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))
2005 QMessageBox::information(this, tr("Sound Effects"), NOBR(tr("All sound effects have been disabled.")));
2006 m_settings->soundsEnabled(false);
2008 else
2010 m_settings->soundsEnabled(true);
2013 else
2015 QMessageBox::information(this, tr("Sound Effects"), NOBR(tr("The sound effects have been re-enabled.")));
2016 m_settings->soundsEnabled(true);
2019 ui->actionDisableSounds->setChecked(!m_settings->soundsEnabled());
2023 * Disable Nero AAC encoder action
2025 void MainWindow::disableNeroAacNotificationsActionTriggered(bool checked)
2027 if(checked)
2029 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))
2031 QMessageBox::information(this, tr("Nero AAC Notifications"), NOBR(tr("All Nero AAC Encoder notifications have been disabled.")));
2032 m_settings->neroAacNotificationsEnabled(false);
2034 else
2036 m_settings->neroAacNotificationsEnabled(true);
2039 else
2041 QMessageBox::information(this, tr("Nero AAC Notifications"), NOBR(tr("The Nero AAC Encoder notifications have been re-enabled.")));
2042 m_settings->neroAacNotificationsEnabled(true);
2045 ui->actionDisableNeroAacNotifications->setChecked(!m_settings->neroAacNotificationsEnabled());
2049 * Disable slow startup action
2051 void MainWindow::disableSlowStartupNotificationsActionTriggered(bool checked)
2053 if(checked)
2055 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))
2057 QMessageBox::information(this, tr("Slow Startup Notifications"), NOBR(tr("The slow startup notifications have been disabled.")));
2058 m_settings->antivirNotificationsEnabled(false);
2060 else
2062 m_settings->antivirNotificationsEnabled(true);
2065 else
2067 QMessageBox::information(this, tr("Slow Startup Notifications"), NOBR(tr("The slow startup notifications have been re-enabled.")));
2068 m_settings->antivirNotificationsEnabled(true);
2071 ui->actionDisableSlowStartupNotifications->setChecked(!m_settings->antivirNotificationsEnabled());
2075 * Import a Cue Sheet file
2077 void MainWindow::importCueSheetActionTriggered(bool checked)
2079 ABORT_IF_BUSY;
2081 TEMP_HIDE_DROPBOX
2083 while(true)
2085 int result = 0;
2086 QString selectedCueFile;
2088 if(MUtils::GUI::themes_enabled())
2090 selectedCueFile = QFileDialog::getOpenFileName(this, tr("Open Cue Sheet"), m_settings->mostRecentInputPath(), QString("%1 (*.cue)").arg(tr("Cue Sheet File")));
2092 else
2094 QFileDialog dialog(this, tr("Open Cue Sheet"));
2095 dialog.setFileMode(QFileDialog::ExistingFile);
2096 dialog.setNameFilter(QString("%1 (*.cue)").arg(tr("Cue Sheet File")));
2097 dialog.setDirectory(m_settings->mostRecentInputPath());
2098 if(dialog.exec())
2100 selectedCueFile = dialog.selectedFiles().first();
2104 if(!selectedCueFile.isEmpty())
2106 m_settings->mostRecentInputPath(QFileInfo(selectedCueFile).canonicalPath());
2107 CueImportDialog *cueImporter = new CueImportDialog(this, m_fileListModel, selectedCueFile, m_settings);
2108 result = cueImporter->exec();
2109 MUTILS_DELETE(cueImporter);
2112 if(result == QDialog::Accepted)
2114 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
2115 ui->sourceFileView->update();
2116 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
2117 ui->sourceFileView->scrollToBottom();
2118 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
2121 if(result != (-1)) break;
2127 * Show the "drop box" widget
2129 void MainWindow::showDropBoxWidgetActionTriggered(bool checked)
2131 m_settings->dropBoxWidgetEnabled(true);
2133 if(!m_dropBox->isVisible())
2135 m_dropBox->show();
2136 QTimer::singleShot(2500, m_dropBox, SLOT(showToolTip()));
2139 MUtils::GUI::blink_window(m_dropBox);
2143 * Check for beta (pre-release) updates
2145 void MainWindow::checkForBetaUpdatesActionTriggered(bool checked)
2147 bool checkUpdatesNow = false;
2149 if(checked)
2151 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))
2153 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")))
2155 checkUpdatesNow = true;
2157 m_settings->autoUpdateCheckBeta(true);
2159 else
2161 m_settings->autoUpdateCheckBeta(false);
2164 else
2166 QMessageBox::information(this, tr("Beta Updates"), NOBR(tr("LameXP will <i>not</i> check for Beta (pre-release) updates from now on.")));
2167 m_settings->autoUpdateCheckBeta(false);
2170 ui->actionCheckForBetaUpdates->setChecked(m_settings->autoUpdateCheckBeta());
2172 if(checkUpdatesNow)
2174 if(checkForUpdates())
2176 QApplication::quit();
2182 * Hibernate computer action
2184 void MainWindow::hibernateComputerActionTriggered(bool checked)
2186 if(checked)
2188 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))
2190 QMessageBox::information(this, tr("Hibernate Computer"), NOBR(tr("LameXP will hibernate the computer on shutdown from now on.")));
2191 m_settings->hibernateComputer(true);
2193 else
2195 m_settings->hibernateComputer(false);
2198 else
2200 QMessageBox::information(this, tr("Hibernate Computer"), NOBR(tr("LameXP will <i>not</i> hibernate the computer on shutdown from now on.")));
2201 m_settings->hibernateComputer(false);
2204 ui->actionHibernateComputer->setChecked(m_settings->hibernateComputer());
2208 * Disable shell integration action
2210 void MainWindow::disableShellIntegrationActionTriggered(bool checked)
2212 if(checked)
2214 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))
2216 ShellIntegration::remove();
2217 QMessageBox::information(this, tr("Shell Integration"), NOBR(tr("The LameXP shell integration has been disabled.")));
2218 m_settings->shellIntegrationEnabled(false);
2220 else
2222 m_settings->shellIntegrationEnabled(true);
2225 else
2227 ShellIntegration::install();
2228 QMessageBox::information(this, tr("Shell Integration"), NOBR(tr("The LameXP shell integration has been re-enabled.")));
2229 m_settings->shellIntegrationEnabled(true);
2232 ui->actionDisableShellIntegration->setChecked(!m_settings->shellIntegrationEnabled());
2234 if(lamexp_version_portable() && ui->actionDisableShellIntegration->isChecked())
2236 ui->actionDisableShellIntegration->setEnabled(false);
2240 // =========================================================
2241 // Help menu slots
2242 // =========================================================
2245 * Visit homepage action
2247 void MainWindow::visitHomepageActionActivated(void)
2249 if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
2251 if(action->data().isValid() && (action->data().type() == QVariant::String))
2253 QDesktopServices::openUrl(QUrl(action->data().toString()));
2259 * Show document
2261 void MainWindow::documentActionActivated(void)
2263 if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
2265 openDocumentLink(action);
2270 * Check for updates action
2272 void MainWindow::checkUpdatesActionActivated(void)
2274 ABORT_IF_BUSY;
2275 bool bFlag = false;
2277 TEMP_HIDE_DROPBOX
2279 bFlag = checkForUpdates();
2282 if(bFlag)
2284 QApplication::quit();
2288 // =========================================================
2289 // Source file slots
2290 // =========================================================
2293 * Add file(s) button
2295 void MainWindow::addFilesButtonClicked(void)
2297 ABORT_IF_BUSY;
2299 TEMP_HIDE_DROPBOX
2301 if(MUtils::GUI::themes_enabled())
2303 QStringList fileTypeFilters = DecoderRegistry::getSupportedTypes();
2304 QStringList selectedFiles = QFileDialog::getOpenFileNames(this, tr("Add file(s)"), m_settings->mostRecentInputPath(), fileTypeFilters.join(";;"));
2305 if(!selectedFiles.isEmpty())
2307 m_settings->mostRecentInputPath(QFileInfo(selectedFiles.first()).canonicalPath());
2308 addFiles(selectedFiles);
2311 else
2313 QFileDialog dialog(this, tr("Add file(s)"));
2314 QStringList fileTypeFilters = DecoderRegistry::getSupportedTypes();
2315 dialog.setFileMode(QFileDialog::ExistingFiles);
2316 dialog.setNameFilter(fileTypeFilters.join(";;"));
2317 dialog.setDirectory(m_settings->mostRecentInputPath());
2318 if(dialog.exec())
2320 QStringList selectedFiles = dialog.selectedFiles();
2321 if(!selectedFiles.isEmpty())
2323 m_settings->mostRecentInputPath(QFileInfo(selectedFiles.first()).canonicalPath());
2324 addFiles(selectedFiles);
2332 * Open folder action
2334 void MainWindow::openFolderActionActivated(void)
2336 ABORT_IF_BUSY;
2337 QString selectedFolder;
2339 if(QAction *action = dynamic_cast<QAction*>(QObject::sender()))
2341 TEMP_HIDE_DROPBOX
2343 if(MUtils::GUI::themes_enabled())
2345 selectedFolder = QFileDialog::getExistingDirectory(this, tr("Add Folder"), m_settings->mostRecentInputPath());
2347 else
2349 QFileDialog dialog(this, tr("Add Folder"));
2350 dialog.setFileMode(QFileDialog::DirectoryOnly);
2351 dialog.setDirectory(m_settings->mostRecentInputPath());
2352 if(dialog.exec())
2354 selectedFolder = dialog.selectedFiles().first();
2358 if(!selectedFolder.isEmpty())
2360 m_settings->mostRecentInputPath(QDir(selectedFolder).canonicalPath());
2361 addFolder(selectedFolder, action->data().toBool());
2368 * Remove file button
2370 void MainWindow::removeFileButtonClicked(void)
2372 if(ui->sourceFileView->currentIndex().isValid())
2374 int iRow = ui->sourceFileView->currentIndex().row();
2375 m_fileListModel->removeFile(ui->sourceFileView->currentIndex());
2376 ui->sourceFileView->selectRow(iRow < m_fileListModel->rowCount() ? iRow : m_fileListModel->rowCount()-1);
2381 * Clear files button
2383 void MainWindow::clearFilesButtonClicked(void)
2385 m_fileListModel->clearFiles();
2389 * Move file up button
2391 void MainWindow::fileUpButtonClicked(void)
2393 if(ui->sourceFileView->currentIndex().isValid())
2395 int iRow = ui->sourceFileView->currentIndex().row() - 1;
2396 m_fileListModel->moveFile(ui->sourceFileView->currentIndex(), -1);
2397 ui->sourceFileView->selectRow(iRow >= 0 ? iRow : 0);
2402 * Move file down button
2404 void MainWindow::fileDownButtonClicked(void)
2406 if(ui->sourceFileView->currentIndex().isValid())
2408 int iRow = ui->sourceFileView->currentIndex().row() + 1;
2409 m_fileListModel->moveFile(ui->sourceFileView->currentIndex(), 1);
2410 ui->sourceFileView->selectRow(iRow < m_fileListModel->rowCount() ? iRow : m_fileListModel->rowCount()-1);
2415 * Show details button
2417 void MainWindow::showDetailsButtonClicked(void)
2419 ABORT_IF_BUSY;
2421 int iResult = 0;
2422 MetaInfoDialog *metaInfoDialog = new MetaInfoDialog(this);
2423 QModelIndex index = ui->sourceFileView->currentIndex();
2425 while(index.isValid())
2427 if(iResult > 0)
2429 index = m_fileListModel->index(index.row() + 1, index.column());
2430 ui->sourceFileView->selectRow(index.row());
2432 if(iResult < 0)
2434 index = m_fileListModel->index(index.row() - 1, index.column());
2435 ui->sourceFileView->selectRow(index.row());
2438 AudioFileModel &file = (*m_fileListModel)[index];
2439 TEMP_HIDE_DROPBOX
2441 iResult = metaInfoDialog->exec(file, index.row() > 0, index.row() < m_fileListModel->rowCount() - 1);
2444 //Copy all info to Meta Info tab
2445 if(iResult == INT_MAX)
2447 m_metaInfoModel->assignInfoFrom(file);
2448 ui->tabWidget->setCurrentIndex(ui->tabWidget->indexOf(ui->tabMetaData));
2449 break;
2452 if(!iResult) break;
2455 MUTILS_DELETE(metaInfoDialog);
2456 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
2457 sourceFilesScrollbarMoved(0);
2461 * Show context menu for source files
2463 void MainWindow::sourceFilesContextMenu(const QPoint &pos)
2465 QAbstractScrollArea *scrollArea = dynamic_cast<QAbstractScrollArea*>(QObject::sender());
2466 QWidget *sender = scrollArea ? scrollArea->viewport() : dynamic_cast<QWidget*>(QObject::sender());
2468 if(sender)
2470 if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0)
2472 m_sourceFilesContextMenu->popup(sender->mapToGlobal(pos));
2478 * Scrollbar of source files moved
2480 void MainWindow::sourceFilesScrollbarMoved(int)
2482 ui->sourceFileView->resizeColumnToContents(0);
2486 * Open selected file in external player
2488 void MainWindow::previewContextActionTriggered(void)
2490 QModelIndex index = ui->sourceFileView->currentIndex();
2491 if(!index.isValid())
2493 return;
2496 if(!MUtils::OS::open_media_file(m_fileListModel->getFile(index).filePath()))
2498 qDebug("Player not found, falling back to default application...");
2499 QDesktopServices::openUrl(QString("file:///").append(m_fileListModel->getFile(index).filePath()));
2504 * Find selected file in explorer
2506 void MainWindow::findFileContextActionTriggered(void)
2508 QModelIndex index = ui->sourceFileView->currentIndex();
2509 if(index.isValid())
2511 QString systemRootPath;
2513 QDir systemRoot(MUtils::OS::known_folder(MUtils::OS::FOLDER_SYSTEMFOLDER));
2514 if(systemRoot.exists() && systemRoot.cdUp())
2516 systemRootPath = systemRoot.canonicalPath();
2519 if(!systemRootPath.isEmpty())
2521 QFileInfo explorer(QString("%1/explorer.exe").arg(systemRootPath));
2522 if(explorer.exists() && explorer.isFile())
2524 QProcess::execute(explorer.canonicalFilePath(), QStringList() << "/select," << QDir::toNativeSeparators(m_fileListModel->getFile(index).filePath()));
2525 return;
2528 else
2530 qWarning("SystemRoot directory could not be detected!");
2536 * Add all dropped files
2538 void MainWindow::handleDroppedFiles(void)
2540 ABORT_IF_BUSY;
2542 static const int MIN_COUNT = 16;
2543 const QString bannerText = tr("Loading dropped files or folders, please wait...");
2544 bool bUseBanner = false;
2546 SHOW_BANNER_CONDITIONALLY(bUseBanner, (m_droppedFileList->count() >= MIN_COUNT), bannerText);
2548 QStringList droppedFiles;
2549 while(!m_droppedFileList->isEmpty())
2551 QFileInfo file(m_droppedFileList->takeFirst().toLocalFile());
2552 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
2554 if(!file.exists())
2556 continue;
2559 if(file.isFile())
2561 qDebug("Dropped File: %s", MUTILS_UTF8(file.canonicalFilePath()));
2562 droppedFiles << file.canonicalFilePath();
2563 continue;
2566 if(file.isDir())
2568 qDebug("Dropped Folder: %s", MUTILS_UTF8(file.canonicalFilePath()));
2569 QFileInfoList list = QDir(file.canonicalFilePath()).entryInfoList(QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks);
2570 if(list.count() > 0)
2572 SHOW_BANNER_CONDITIONALLY(bUseBanner, (list.count() >= MIN_COUNT), bannerText);
2573 for(QFileInfoList::ConstIterator iter = list.constBegin(); iter != list.constEnd(); iter++)
2575 droppedFiles << (*iter).canonicalFilePath();
2578 else
2580 list = QDir(file.canonicalFilePath()).entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks);
2581 SHOW_BANNER_CONDITIONALLY(bUseBanner, (list.count() >= MIN_COUNT), bannerText);
2582 for(QFileInfoList::ConstIterator iter = list.constBegin(); iter != list.constEnd(); iter++)
2584 qDebug("Descending to Folder: %s", MUTILS_UTF8((*iter).canonicalFilePath()));
2585 m_droppedFileList->prepend(QUrl::fromLocalFile((*iter).canonicalFilePath()));
2591 if(bUseBanner)
2593 m_banner->close();
2596 if(!droppedFiles.isEmpty())
2598 addFiles(droppedFiles);
2603 * Add all pending files
2605 void MainWindow::handleDelayedFiles(void)
2607 m_delayedFileTimer->stop();
2609 if(m_delayedFileList->isEmpty())
2611 return;
2614 if(BANNER_VISIBLE)
2616 m_delayedFileTimer->start(5000);
2617 return;
2620 WITH_BLOCKED_SIGNALS(ui->tabWidget, setCurrentIndex, 0);
2621 tabPageChanged(ui->tabWidget->currentIndex(), true);
2623 QStringList selectedFiles;
2624 while(!m_delayedFileList->isEmpty())
2626 QFileInfo currentFile = QFileInfo(m_delayedFileList->takeFirst());
2627 if(!currentFile.exists() || !currentFile.isFile())
2629 continue;
2631 selectedFiles << currentFile.canonicalFilePath();
2634 addFiles(selectedFiles);
2638 * Export Meta tags to CSV file
2640 void MainWindow::exportCsvContextActionTriggered(void)
2642 TEMP_HIDE_DROPBOX
2644 QString selectedCsvFile;
2646 if(MUtils::GUI::themes_enabled())
2648 selectedCsvFile = QFileDialog::getSaveFileName(this, tr("Save CSV file"), m_settings->mostRecentInputPath(), QString("%1 (*.csv)").arg(tr("CSV File")));
2650 else
2652 QFileDialog dialog(this, tr("Save CSV file"));
2653 dialog.setFileMode(QFileDialog::AnyFile);
2654 dialog.setAcceptMode(QFileDialog::AcceptSave);
2655 dialog.setNameFilter(QString("%1 (*.csv)").arg(tr("CSV File")));
2656 dialog.setDirectory(m_settings->mostRecentInputPath());
2657 if(dialog.exec())
2659 selectedCsvFile = dialog.selectedFiles().first();
2663 if(!selectedCsvFile.isEmpty())
2665 m_settings->mostRecentInputPath(QFileInfo(selectedCsvFile).canonicalPath());
2666 switch(m_fileListModel->exportToCsv(selectedCsvFile))
2668 case FileListModel::CsvError_NoTags:
2669 QMessageBox::critical(this, tr("CSV Export"), NOBR(tr("Sorry, there are no meta tags that can be exported!")));
2670 break;
2671 case FileListModel::CsvError_FileOpen:
2672 QMessageBox::critical(this, tr("CSV Export"), NOBR(tr("Sorry, failed to open CSV file for writing!")));
2673 break;
2674 case FileListModel::CsvError_FileWrite:
2675 QMessageBox::critical(this, tr("CSV Export"), NOBR(tr("Sorry, failed to write to the CSV file!")));
2676 break;
2677 case FileListModel::CsvError_OK:
2678 QMessageBox::information(this, tr("CSV Export"), NOBR(tr("The CSV files was created successfully!")));
2679 break;
2680 default:
2681 qWarning("exportToCsv: Unknown return code!");
2689 * Import Meta tags from CSV file
2691 void MainWindow::importCsvContextActionTriggered(void)
2693 TEMP_HIDE_DROPBOX
2695 QString selectedCsvFile;
2697 if(MUtils::GUI::themes_enabled())
2699 selectedCsvFile = QFileDialog::getOpenFileName(this, tr("Open CSV file"), m_settings->mostRecentInputPath(), QString("%1 (*.csv)").arg(tr("CSV File")));
2701 else
2703 QFileDialog dialog(this, tr("Open CSV file"));
2704 dialog.setFileMode(QFileDialog::ExistingFile);
2705 dialog.setNameFilter(QString("%1 (*.csv)").arg(tr("CSV File")));
2706 dialog.setDirectory(m_settings->mostRecentInputPath());
2707 if(dialog.exec())
2709 selectedCsvFile = dialog.selectedFiles().first();
2713 if(!selectedCsvFile.isEmpty())
2715 m_settings->mostRecentInputPath(QFileInfo(selectedCsvFile).canonicalPath());
2716 switch(m_fileListModel->importFromCsv(this, selectedCsvFile))
2718 case FileListModel::CsvError_FileOpen:
2719 QMessageBox::critical(this, tr("CSV Import"), NOBR(tr("Sorry, failed to open CSV file for reading!")));
2720 break;
2721 case FileListModel::CsvError_FileRead:
2722 QMessageBox::critical(this, tr("CSV Import"), NOBR(tr("Sorry, failed to read from the CSV file!")));
2723 break;
2724 case FileListModel::CsvError_NoTags:
2725 QMessageBox::critical(this, tr("CSV Import"), NOBR(tr("Sorry, the CSV file does not contain any known fields!")));
2726 break;
2727 case FileListModel::CsvError_Incomplete:
2728 QMessageBox::warning(this, tr("CSV Import"), NOBR(tr("CSV file is incomplete. Not all files were updated!")));
2729 break;
2730 case FileListModel::CsvError_OK:
2731 QMessageBox::information(this, tr("CSV Import"), NOBR(tr("The CSV files was imported successfully!")));
2732 break;
2733 case FileListModel::CsvError_Aborted:
2734 /* User aborted, ignore! */
2735 break;
2736 default:
2737 qWarning("exportToCsv: Unknown return code!");
2744 * Show or hide Drag'n'Drop notice after model reset
2746 void MainWindow::sourceModelChanged(void)
2748 m_dropNoteLabel->setVisible(m_fileListModel->rowCount() <= 0);
2751 // =========================================================
2752 // Output folder slots
2753 // =========================================================
2756 * Output folder changed (mouse clicked)
2758 void MainWindow::outputFolderViewClicked(const QModelIndex &index)
2760 if(index.isValid() && (ui->outputFolderView->currentIndex() != index))
2762 ui->outputFolderView->setCurrentIndex(index);
2765 if(m_fileSystemModel && index.isValid())
2767 QString selectedDir = m_fileSystemModel->filePath(index);
2768 if(selectedDir.length() < 3) selectedDir.append(QDir::separator());
2769 ui->outputFolderLabel->setText(QDir::toNativeSeparators(selectedDir));
2770 ui->outputFolderLabel->setToolTip(ui->outputFolderLabel->text());
2771 m_settings->outputDir(selectedDir);
2773 else
2775 ui->outputFolderLabel->setText(QDir::toNativeSeparators(m_settings->outputDir()));
2776 ui->outputFolderLabel->setToolTip(ui->outputFolderLabel->text());
2781 * Output folder changed (mouse moved)
2783 void MainWindow::outputFolderViewMoved(const QModelIndex &index)
2785 if(QApplication::mouseButtons() & Qt::LeftButton)
2787 outputFolderViewClicked(index);
2792 * Goto desktop button
2794 void MainWindow::gotoDesktopButtonClicked(void)
2796 if(!m_fileSystemModel)
2798 qWarning("File system model not initialized yet!");
2799 return;
2802 QString desktopPath = QDesktopServices::storageLocation(QDesktopServices::DesktopLocation);
2804 if(!desktopPath.isEmpty() && QDir(desktopPath).exists())
2806 ui->outputFolderView->setCurrentIndex(m_fileSystemModel->index(desktopPath));
2807 outputFolderViewClicked(ui->outputFolderView->currentIndex());
2808 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2810 else
2812 ui->buttonGotoDesktop->setEnabled(false);
2817 * Goto home folder button
2819 void MainWindow::gotoHomeFolderButtonClicked(void)
2821 if(!m_fileSystemModel)
2823 qWarning("File system model not initialized yet!");
2824 return;
2827 QString homePath = QDesktopServices::storageLocation(QDesktopServices::HomeLocation);
2829 if(!homePath.isEmpty() && QDir(homePath).exists())
2831 ui->outputFolderView->setCurrentIndex(m_fileSystemModel->index(homePath));
2832 outputFolderViewClicked(ui->outputFolderView->currentIndex());
2833 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2835 else
2837 ui->buttonGotoHome->setEnabled(false);
2842 * Goto music folder button
2844 void MainWindow::gotoMusicFolderButtonClicked(void)
2846 if(!m_fileSystemModel)
2848 qWarning("File system model not initialized yet!");
2849 return;
2852 QString musicPath = QDesktopServices::storageLocation(QDesktopServices::MusicLocation);
2854 if(!musicPath.isEmpty() && QDir(musicPath).exists())
2856 ui->outputFolderView->setCurrentIndex(m_fileSystemModel->index(musicPath));
2857 outputFolderViewClicked(ui->outputFolderView->currentIndex());
2858 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2860 else
2862 ui->buttonGotoMusic->setEnabled(false);
2867 * Goto music favorite output folder
2869 void MainWindow::gotoFavoriteFolder(void)
2871 if(!m_fileSystemModel)
2873 qWarning("File system model not initialized yet!");
2874 return;
2877 QAction *item = dynamic_cast<QAction*>(QObject::sender());
2879 if(item)
2881 QDir path(item->data().toString());
2882 if(path.exists())
2884 ui->outputFolderView->setCurrentIndex(m_fileSystemModel->index(path.canonicalPath()));
2885 outputFolderViewClicked(ui->outputFolderView->currentIndex());
2886 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2888 else
2890 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
2891 m_outputFolderFavoritesMenu->removeAction(item);
2892 item->deleteLater();
2898 * Make folder button
2900 void MainWindow::makeFolderButtonClicked(void)
2902 ABORT_IF_BUSY;
2904 if(!m_fileSystemModel)
2906 qWarning("File system model not initialized yet!");
2907 return;
2910 QDir basePath(m_fileSystemModel->fileInfo(ui->outputFolderView->currentIndex()).absoluteFilePath());
2911 QString suggestedName = tr("New Folder");
2913 if(!m_metaData->artist().isEmpty() && !m_metaData->album().isEmpty())
2915 suggestedName = QString("%1 - %2").arg(m_metaData->artist(),m_metaData->album());
2917 else if(!m_metaData->artist().isEmpty())
2919 suggestedName = m_metaData->artist();
2921 else if(!m_metaData->album().isEmpty())
2923 suggestedName =m_metaData->album();
2925 else
2927 for(int i = 0; i < m_fileListModel->rowCount(); i++)
2929 const AudioFileModel &audioFile = m_fileListModel->getFile(m_fileListModel->index(i, 0));
2930 const AudioFileModel_MetaInfo &fileMetaInfo = audioFile.metaInfo();
2932 if(!fileMetaInfo.album().isEmpty() || !fileMetaInfo.artist().isEmpty())
2934 if(!fileMetaInfo.artist().isEmpty() && !fileMetaInfo.album().isEmpty())
2936 suggestedName = QString("%1 - %2").arg(fileMetaInfo.artist(), fileMetaInfo.album());
2938 else if(!fileMetaInfo.artist().isEmpty())
2940 suggestedName = fileMetaInfo.artist();
2942 else if(!fileMetaInfo.album().isEmpty())
2944 suggestedName = fileMetaInfo.album();
2946 break;
2951 suggestedName = MUtils::clean_file_name(suggestedName);
2953 while(true)
2955 bool bApplied = false;
2956 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();
2958 if(bApplied)
2960 folderName = MUtils::clean_file_path(folderName.simplified());
2962 if(folderName.isEmpty())
2964 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
2965 continue;
2968 int i = 1;
2969 QString newFolder = folderName;
2971 while(basePath.exists(newFolder))
2973 newFolder = QString(folderName).append(QString().sprintf(" (%d)", ++i));
2976 if(basePath.mkpath(newFolder))
2978 QDir createdDir = basePath;
2979 if(createdDir.cd(newFolder))
2981 QModelIndex newIndex = m_fileSystemModel->index(createdDir.canonicalPath());
2982 ui->outputFolderView->setCurrentIndex(newIndex);
2983 outputFolderViewClicked(newIndex);
2984 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
2987 else
2989 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!")));
2992 break;
2997 * Output to source dir changed
2999 void MainWindow::saveToSourceFolderChanged(void)
3001 m_settings->outputToSourceDir(ui->saveToSourceFolderCheckBox->isChecked());
3005 * Prepend relative source file path to output file name changed
3007 void MainWindow::prependRelativePathChanged(void)
3009 m_settings->prependRelativeSourcePath(ui->prependRelativePathCheckBox->isChecked());
3013 * Show context menu for output folder
3015 void MainWindow::outputFolderContextMenu(const QPoint &pos)
3017 QAbstractScrollArea *scrollArea = dynamic_cast<QAbstractScrollArea*>(QObject::sender());
3018 QWidget *sender = scrollArea ? scrollArea->viewport() : dynamic_cast<QWidget*>(QObject::sender());
3020 if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0)
3022 m_outputFolderContextMenu->popup(sender->mapToGlobal(pos));
3027 * Show selected folder in explorer
3029 void MainWindow::showFolderContextActionTriggered(void)
3031 if(!m_fileSystemModel)
3033 qWarning("File system model not initialized yet!");
3034 return;
3037 QString path = QDir::toNativeSeparators(m_fileSystemModel->filePath(ui->outputFolderView->currentIndex()));
3038 if(!path.endsWith(QDir::separator())) path.append(QDir::separator());
3039 MUtils::OS::shell_open(this, path, true);
3043 * Refresh the directory outline
3045 void MainWindow::refreshFolderContextActionTriggered(void)
3047 //force re-initialization
3048 QTimer::singleShot(0, this, SLOT(initOutputFolderModel()));
3052 * Go one directory up
3054 void MainWindow::goUpFolderContextActionTriggered(void)
3056 QModelIndex current = ui->outputFolderView->currentIndex();
3057 if(current.isValid())
3059 QModelIndex parent = current.parent();
3060 if(parent.isValid())
3063 ui->outputFolderView->setCurrentIndex(parent);
3064 outputFolderViewClicked(parent);
3066 else
3068 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN);
3070 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
3075 * Add current folder to favorites
3077 void MainWindow::addFavoriteFolderActionTriggered(void)
3079 QString path = m_fileSystemModel->filePath(ui->outputFolderView->currentIndex());
3080 QStringList favorites = m_settings->favoriteOutputFolders().split("|", QString::SkipEmptyParts);
3082 if(!favorites.contains(path, Qt::CaseInsensitive))
3084 favorites.append(path);
3085 while(favorites.count() > 6) favorites.removeFirst();
3087 else
3089 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN);
3092 m_settings->favoriteOutputFolders(favorites.join("|"));
3093 refreshFavorites();
3097 * Output folder edit finished
3099 void MainWindow::outputFolderEditFinished(void)
3101 if(ui->outputFolderEdit->isHidden())
3103 return; //Not currently in edit mode!
3106 bool ok = false;
3108 QString text = QDir::fromNativeSeparators(ui->outputFolderEdit->text().trimmed());
3109 while(text.startsWith('"') || text.startsWith('/')) text = text.right(text.length() - 1).trimmed();
3110 while(text.endsWith('"') || text.endsWith('/')) text = text.left(text.length() - 1).trimmed();
3112 static const char *str = "?*<>|\"";
3113 for(size_t i = 0; str[i]; i++) text.replace(str[i], "_");
3115 if(!((text.length() >= 2) && text.at(0).isLetter() && text.at(1) == QChar(':')))
3117 text = QString("%1/%2").arg(QDir::fromNativeSeparators(ui->outputFolderLabel->text()), text);
3120 if(text.length() == 2) text += "/"; /* "X:" => "X:/" */
3122 while(text.length() > 2)
3124 QFileInfo info(text);
3125 if(info.exists() && info.isDir())
3127 QModelIndex index = m_fileSystemModel->index(QFileInfo(info.canonicalFilePath()).absoluteFilePath());
3128 if(index.isValid())
3130 ok = true;
3131 ui->outputFolderView->setCurrentIndex(index);
3132 outputFolderViewClicked(index);
3133 break;
3136 else if(info.exists() && info.isFile())
3138 QModelIndex index = m_fileSystemModel->index(QFileInfo(info.canonicalPath()).absoluteFilePath());
3139 if(index.isValid())
3141 ok = true;
3142 ui->outputFolderView->setCurrentIndex(index);
3143 outputFolderViewClicked(index);
3144 break;
3148 text = text.left(text.length() - 1).trimmed();
3151 ui->outputFolderEdit->setVisible(false);
3152 ui->outputFolderLabel->setVisible(true);
3153 ui->outputFolderView->setEnabled(true);
3155 if(!ok) MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
3156 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
3160 * Initialize file system model
3162 void MainWindow::initOutputFolderModel(void)
3164 if(m_outputFolderNoteBox->isHidden())
3166 m_outputFolderNoteBox->show();
3167 m_outputFolderNoteBox->repaint();
3168 m_outputFolderViewInitCounter = 4;
3170 if(m_fileSystemModel)
3172 SET_MODEL(ui->outputFolderView, NULL);
3173 MUTILS_DELETE(m_fileSystemModel);
3174 ui->outputFolderView->repaint();
3177 if(m_fileSystemModel = new QFileSystemModelEx())
3179 m_fileSystemModel->installEventFilter(this);
3180 connect(m_fileSystemModel, SIGNAL(directoryLoaded(QString)), this, SLOT(outputFolderDirectoryLoaded(QString)));
3181 connect(m_fileSystemModel, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(outputFolderRowsInserted(QModelIndex,int,int)));
3183 SET_MODEL(ui->outputFolderView, m_fileSystemModel);
3184 ui->outputFolderView->header()->setStretchLastSection(true);
3185 ui->outputFolderView->header()->hideSection(1);
3186 ui->outputFolderView->header()->hideSection(2);
3187 ui->outputFolderView->header()->hideSection(3);
3189 m_fileSystemModel->setRootPath("");
3190 QModelIndex index = m_fileSystemModel->index(m_settings->outputDir());
3191 if(index.isValid()) ui->outputFolderView->setCurrentIndex(index);
3192 outputFolderViewClicked(ui->outputFolderView->currentIndex());
3195 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
3196 QTimer::singleShot(125, this, SLOT(initOutputFolderModel_doAsync()));
3201 * Initialize file system model (do NOT call this one directly!)
3203 void MainWindow::initOutputFolderModel_doAsync(void)
3205 if(m_outputFolderViewInitCounter > 0)
3207 m_outputFolderViewInitCounter--;
3208 QTimer::singleShot(125, this, SLOT(initOutputFolderModel_doAsync()));
3210 else
3212 QTimer::singleShot(125, m_outputFolderNoteBox, SLOT(hide()));
3213 ui->outputFolderView->setFocus();
3218 * Center current folder in view
3220 void MainWindow::centerOutputFolderModel(void)
3222 if(ui->outputFolderView->isVisible())
3224 centerOutputFolderModel_doAsync();
3225 QTimer::singleShot(125, this, SLOT(centerOutputFolderModel_doAsync()));
3230 * Center current folder in view (do NOT call this one directly!)
3232 void MainWindow::centerOutputFolderModel_doAsync(void)
3234 if(ui->outputFolderView->isVisible())
3236 m_outputFolderViewCentering = true;
3237 const QModelIndex index = ui->outputFolderView->currentIndex();
3238 ui->outputFolderView->scrollTo(index, QAbstractItemView::PositionAtCenter);
3239 ui->outputFolderView->setFocus();
3244 * File system model asynchronously loaded a dir
3246 void MainWindow::outputFolderDirectoryLoaded(const QString &path)
3248 if(m_outputFolderViewCentering)
3250 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
3255 * File system model inserted new items
3257 void MainWindow::outputFolderRowsInserted(const QModelIndex &parent, int start, int end)
3259 if(m_outputFolderViewCentering)
3261 CENTER_CURRENT_OUTPUT_FOLDER_DELAYED;
3266 * Directory view item was expanded by user
3268 void MainWindow::outputFolderItemExpanded(const QModelIndex &item)
3270 //We need to stop centering as soon as the user has expanded an item manually!
3271 m_outputFolderViewCentering = false;
3275 * View event for output folder control occurred
3277 void MainWindow::outputFolderViewEventOccurred(QWidget *sender, QEvent *event)
3279 switch(event->type())
3281 case QEvent::Enter:
3282 case QEvent::Leave:
3283 case QEvent::KeyPress:
3284 case QEvent::KeyRelease:
3285 case QEvent::FocusIn:
3286 case QEvent::FocusOut:
3287 case QEvent::TouchEnd:
3288 outputFolderViewClicked(ui->outputFolderView->currentIndex());
3289 break;
3294 * Mouse event for output folder control occurred
3296 void MainWindow::outputFolderMouseEventOccurred(QWidget *sender, QEvent *event)
3298 QMouseEvent *mouseEvent = dynamic_cast<QMouseEvent*>(event);
3299 QPoint pos = (mouseEvent) ? mouseEvent->pos() : QPoint();
3301 if(sender == ui->outputFolderLabel)
3303 switch(event->type())
3305 case QEvent::MouseButtonPress:
3306 if(mouseEvent && (mouseEvent->button() == Qt::LeftButton))
3308 QString path = ui->outputFolderLabel->text();
3309 if(!path.endsWith(QDir::separator())) path.append(QDir::separator());
3310 MUtils::OS::shell_open(this, path, true);
3312 break;
3313 case QEvent::Enter:
3314 ui->outputFolderLabel->setForegroundRole(QPalette::Link);
3315 break;
3316 case QEvent::Leave:
3317 ui->outputFolderLabel->setForegroundRole(QPalette::WindowText);
3318 break;
3322 if((sender == ui->outputFoldersFovoritesLabel) || (sender == ui->outputFoldersEditorLabel) || (sender == ui->outputFoldersGoUpLabel))
3324 const type_info &styleType = typeid(*qApp->style());
3325 if((typeid(QPlastiqueStyle) == styleType) || (typeid(QWindowsStyle) == styleType))
3327 switch(event->type())
3329 case QEvent::Enter:
3330 dynamic_cast<QLabel*>(sender)->setFrameShadow(ui->outputFolderView->isEnabled() ? QFrame::Raised : QFrame::Plain);
3331 break;
3332 case QEvent::MouseButtonPress:
3333 dynamic_cast<QLabel*>(sender)->setFrameShadow(ui->outputFolderView->isEnabled() ? QFrame::Sunken : QFrame::Plain);
3334 break;
3335 case QEvent::MouseButtonRelease:
3336 dynamic_cast<QLabel*>(sender)->setFrameShadow(ui->outputFolderView->isEnabled() ? QFrame::Raised : QFrame::Plain);
3337 break;
3338 case QEvent::Leave:
3339 dynamic_cast<QLabel*>(sender)->setFrameShadow(ui->outputFolderView->isEnabled() ? QFrame::Plain : QFrame::Plain);
3340 break;
3343 else
3345 dynamic_cast<QLabel*>(sender)->setFrameShadow(QFrame::Plain);
3348 if((event->type() == QEvent::MouseButtonRelease) && ui->outputFolderView->isEnabled() && (mouseEvent))
3350 if(pos.x() <= sender->width() && pos.y() <= sender->height() && pos.x() >= 0 && pos.y() >= 0 && mouseEvent->button() != Qt::MidButton)
3352 if(sender == ui->outputFoldersFovoritesLabel)
3354 m_outputFolderFavoritesMenu->popup(sender->mapToGlobal(pos));
3356 else if(sender == ui->outputFoldersEditorLabel)
3358 ui->outputFolderView->setEnabled(false);
3359 ui->outputFolderLabel->setVisible(false);
3360 ui->outputFolderEdit->setVisible(true);
3361 ui->outputFolderEdit->setText(ui->outputFolderLabel->text());
3362 ui->outputFolderEdit->selectAll();
3363 ui->outputFolderEdit->setFocus();
3365 else if(sender == ui->outputFoldersGoUpLabel)
3367 QTimer::singleShot(0, this, SLOT(goUpFolderContextActionTriggered()));
3369 else
3371 MUTILS_THROW("Oups, this is not supposed to happen!");
3378 // =========================================================
3379 // Metadata tab slots
3380 // =========================================================
3383 * Edit meta button clicked
3385 void MainWindow::editMetaButtonClicked(void)
3387 ABORT_IF_BUSY;
3389 const QModelIndex index = ui->metaDataView->currentIndex();
3391 if(index.isValid())
3393 m_metaInfoModel->editItem(index, this);
3395 if(index.row() == 4)
3397 m_settings->metaInfoPosition(m_metaData->position());
3403 * Reset meta button clicked
3405 void MainWindow::clearMetaButtonClicked(void)
3407 ABORT_IF_BUSY;
3408 m_metaInfoModel->clearData();
3412 * Meta tags enabled changed
3414 void MainWindow::metaTagsEnabledChanged(void)
3416 m_settings->writeMetaTags(ui->writeMetaDataCheckBox->isChecked());
3420 * Playlist enabled changed
3422 void MainWindow::playlistEnabledChanged(void)
3424 m_settings->createPlaylist(ui->generatePlaylistCheckBox->isChecked());
3427 // =========================================================
3428 // Compression tab slots
3429 // =========================================================
3432 * Update encoder
3434 void MainWindow::updateEncoder(int id)
3436 /*qWarning("\nupdateEncoder(%d)", id);*/
3438 m_settings->compressionEncoder(id);
3439 const AbstractEncoderInfo *info = EncoderRegistry::getEncoderInfo(id);
3441 //Update UI controls
3442 ui->radioButtonModeQuality ->setEnabled(info->isModeSupported(SettingsModel::VBRMode));
3443 ui->radioButtonModeAverageBitrate->setEnabled(info->isModeSupported(SettingsModel::ABRMode));
3444 ui->radioButtonConstBitrate ->setEnabled(info->isModeSupported(SettingsModel::CBRMode));
3446 //Initialize checkbox state
3447 if(ui->radioButtonModeQuality->isEnabled()) ui->radioButtonModeQuality->setChecked(true);
3448 else if(ui->radioButtonModeAverageBitrate->isEnabled()) ui->radioButtonModeAverageBitrate->setChecked(true);
3449 else if(ui->radioButtonConstBitrate->isEnabled()) ui->radioButtonConstBitrate->setChecked(true);
3450 else MUTILS_THROW("It appears that the encoder does not support *any* RC mode!");
3452 //Apply current RC mode
3453 const int currentRCMode = EncoderRegistry::loadEncoderMode(m_settings, id);
3454 switch(currentRCMode)
3456 case SettingsModel::VBRMode: if(ui->radioButtonModeQuality->isEnabled()) ui->radioButtonModeQuality->setChecked(true); break;
3457 case SettingsModel::ABRMode: if(ui->radioButtonModeAverageBitrate->isEnabled()) ui->radioButtonModeAverageBitrate->setChecked(true); break;
3458 case SettingsModel::CBRMode: if(ui->radioButtonConstBitrate->isEnabled()) ui->radioButtonConstBitrate->setChecked(true); break;
3459 default: MUTILS_THROW("updateEncoder(): Unknown rc-mode encountered!");
3462 //Display encoder description
3463 if(const char* description = info->description())
3465 ui->labelEncoderInfo->setVisible(true);
3466 ui->labelEncoderInfo->setText(tr("Current Encoder: %1").arg(QString::fromUtf8(description)));
3468 else
3470 ui->labelEncoderInfo->setVisible(false);
3473 //Update RC mode!
3474 updateRCMode(m_modeButtonGroup->checkedId());
3478 * Update rate-control mode
3480 void MainWindow::updateRCMode(int id)
3482 /*qWarning("updateRCMode(%d)", id);*/
3484 //Store new RC mode
3485 const int currentEncoder = m_encoderButtonGroup->checkedId();
3486 EncoderRegistry::saveEncoderMode(m_settings, currentEncoder, id);
3488 //Fetch encoder info
3489 const AbstractEncoderInfo *info = EncoderRegistry::getEncoderInfo(currentEncoder);
3490 const int valueCount = info->valueCount(id);
3492 //Sanity check
3493 if(!info->isModeSupported(id))
3495 qWarning("Attempting to use an unsupported RC mode (%d) with current encoder (%d)!", id, currentEncoder);
3496 ui->labelBitrate->setText("(ERROR)");
3497 return;
3500 //Update slider min/max values
3501 if(valueCount > 0)
3503 WITH_BLOCKED_SIGNALS(ui->sliderBitrate, setEnabled, true);
3504 WITH_BLOCKED_SIGNALS(ui->sliderBitrate, setMinimum, 0);
3505 WITH_BLOCKED_SIGNALS(ui->sliderBitrate, setMaximum, valueCount-1);
3507 else
3509 WITH_BLOCKED_SIGNALS(ui->sliderBitrate, setEnabled, false);
3510 WITH_BLOCKED_SIGNALS(ui->sliderBitrate, setMinimum, 0);
3511 WITH_BLOCKED_SIGNALS(ui->sliderBitrate, setMaximum, 2);
3514 //Now update bitrate/quality value!
3515 if(valueCount > 0)
3517 const int currentValue = EncoderRegistry::loadEncoderValue(m_settings, currentEncoder, id);
3518 ui->sliderBitrate->setValue(qBound(0, currentValue, valueCount-1));
3519 updateBitrate(qBound(0, currentValue, valueCount-1));
3521 else
3523 ui->sliderBitrate->setValue(1);
3524 updateBitrate(0);
3529 * Update bitrate
3531 void MainWindow::updateBitrate(int value)
3533 /*qWarning("updateBitrate(%d)", value);*/
3535 //Load current encoder and RC mode
3536 const int currentEncoder = m_encoderButtonGroup->checkedId();
3537 const int currentRCMode = m_modeButtonGroup->checkedId();
3539 //Fetch encoder info
3540 const AbstractEncoderInfo *info = EncoderRegistry::getEncoderInfo(currentEncoder);
3541 const int valueCount = info->valueCount(currentRCMode);
3543 //Sanity check
3544 if(!info->isModeSupported(currentRCMode))
3546 qWarning("Attempting to use an unsupported RC mode (%d) with current encoder (%d)!", currentRCMode, currentEncoder);
3547 ui->labelBitrate->setText("(ERROR)");
3548 return;
3551 //Store new bitrate value
3552 if(valueCount > 0)
3554 EncoderRegistry::saveEncoderValue(m_settings, currentEncoder, currentRCMode, qBound(0, value, valueCount-1));
3557 //Update bitrate value
3558 const int displayValue = (valueCount > 0) ? info->valueAt(currentRCMode, qBound(0, value, valueCount-1)) : INT_MAX;
3559 switch(info->valueType(currentRCMode))
3561 case AbstractEncoderInfo::TYPE_BITRATE:
3562 ui->labelBitrate->setText(QString("%1 kbps").arg(QString::number(displayValue)));
3563 break;
3564 case AbstractEncoderInfo::TYPE_APPROX_BITRATE:
3565 ui->labelBitrate->setText(QString("&asymp; %1 kbps").arg(QString::number(displayValue)));
3566 break;
3567 case AbstractEncoderInfo::TYPE_QUALITY_LEVEL_INT:
3568 ui->labelBitrate->setText(tr("Quality Level %1").arg(QString::number(displayValue)));
3569 break;
3570 case AbstractEncoderInfo::TYPE_QUALITY_LEVEL_FLT:
3571 ui->labelBitrate->setText(tr("Quality Level %1").arg(QString().sprintf("%.2f", double(displayValue)/100.0)));
3572 break;
3573 case AbstractEncoderInfo::TYPE_COMPRESSION_LEVEL:
3574 ui->labelBitrate->setText(tr("Compression %1").arg(QString::number(displayValue)));
3575 break;
3576 case AbstractEncoderInfo::TYPE_UNCOMPRESSED:
3577 ui->labelBitrate->setText(tr("Uncompressed"));
3578 break;
3579 default:
3580 MUTILS_THROW("Unknown display value type encountered!");
3581 break;
3586 * Event for compression tab occurred
3588 void MainWindow::compressionTabEventOccurred(QWidget *sender, QEvent *event)
3590 static const QUrl helpUrl("http://lamexp.sourceforge.net/doc/FAQ.html#054010d9");
3592 if((sender == ui->labelCompressionHelp) && (event->type() == QEvent::MouseButtonPress))
3594 QDesktopServices::openUrl(helpUrl);
3596 else if((sender == ui->labelResetEncoders) && (event->type() == QEvent::MouseButtonPress))
3598 PLAY_SOUND_OPTIONAL("blast", true);
3599 EncoderRegistry::resetAllEncoders(m_settings);
3600 m_settings->compressionEncoder(SettingsModel::MP3Encoder);
3601 ui->radioButtonEncoderMP3->setChecked(true);
3602 QTimer::singleShot(0, this, SLOT(updateEncoder()));
3606 // =========================================================
3607 // Advanced option slots
3608 // =========================================================
3611 * Lame algorithm quality changed
3613 void MainWindow::updateLameAlgoQuality(int value)
3615 QString text;
3617 switch(value)
3619 case 3:
3620 text = tr("Best Quality (Slow)");
3621 break;
3622 case 2:
3623 text = tr("High Quality (Recommended)");
3624 break;
3625 case 1:
3626 text = tr("Acceptable Quality (Fast)");
3627 break;
3628 case 0:
3629 text = tr("Poor Quality (Very Fast)");
3630 break;
3633 if(!text.isEmpty())
3635 m_settings->lameAlgoQuality(value);
3636 ui->labelLameAlgoQuality->setText(text);
3639 bool warning = (value == 0), notice = (value == 3);
3640 ui->labelLameAlgoQualityWarning->setVisible(warning);
3641 ui->labelLameAlgoQualityWarningIcon->setVisible(warning);
3642 ui->labelLameAlgoQualityNotice->setVisible(notice);
3643 ui->labelLameAlgoQualityNoticeIcon->setVisible(notice);
3644 ui->labelLameAlgoQualitySpacer->setVisible(warning || notice);
3648 * Bitrate management endabled/disabled
3650 void MainWindow::bitrateManagementEnabledChanged(bool checked)
3652 m_settings->bitrateManagementEnabled(checked);
3656 * Minimum bitrate has changed
3658 void MainWindow::bitrateManagementMinChanged(int value)
3660 if(value > ui->spinBoxBitrateManagementMax->value())
3662 ui->spinBoxBitrateManagementMin->setValue(ui->spinBoxBitrateManagementMax->value());
3663 m_settings->bitrateManagementMinRate(ui->spinBoxBitrateManagementMax->value());
3665 else
3667 m_settings->bitrateManagementMinRate(value);
3672 * Maximum bitrate has changed
3674 void MainWindow::bitrateManagementMaxChanged(int value)
3676 if(value < ui->spinBoxBitrateManagementMin->value())
3678 ui->spinBoxBitrateManagementMax->setValue(ui->spinBoxBitrateManagementMin->value());
3679 m_settings->bitrateManagementMaxRate(ui->spinBoxBitrateManagementMin->value());
3681 else
3683 m_settings->bitrateManagementMaxRate(value);
3688 * Channel mode has changed
3690 void MainWindow::channelModeChanged(int value)
3692 if(value >= 0) m_settings->lameChannelMode(value);
3696 * Sampling rate has changed
3698 void MainWindow::samplingRateChanged(int value)
3700 if(value >= 0) m_settings->samplingRate(value);
3704 * Nero AAC 2-Pass mode changed
3706 void MainWindow::neroAAC2PassChanged(bool checked)
3708 m_settings->neroAACEnable2Pass(checked);
3712 * Nero AAC profile mode changed
3714 void MainWindow::neroAACProfileChanged(int value)
3716 if(value >= 0) m_settings->aacEncProfile(value);
3720 * Aften audio coding mode changed
3722 void MainWindow::aftenCodingModeChanged(int value)
3724 if(value >= 0) m_settings->aftenAudioCodingMode(value);
3728 * Aften DRC mode changed
3730 void MainWindow::aftenDRCModeChanged(int value)
3732 if(value >= 0) m_settings->aftenDynamicRangeCompression(value);
3736 * Aften exponent search size changed
3738 void MainWindow::aftenSearchSizeChanged(int value)
3740 if(value >= 0) m_settings->aftenExponentSearchSize(value);
3744 * Aften fast bit allocation changed
3746 void MainWindow::aftenFastAllocationChanged(bool checked)
3748 m_settings->aftenFastBitAllocation(checked);
3753 * Opus encoder settings changed
3755 void MainWindow::opusSettingsChanged(void)
3757 m_settings->opusFramesize(ui->comboBoxOpusFramesize->currentIndex());
3758 m_settings->opusComplexity(ui->spinBoxOpusComplexity->value());
3759 m_settings->opusDisableResample(ui->checkBoxOpusDisableResample->isChecked());
3763 * Normalization filter enabled changed
3765 void MainWindow::normalizationEnabledChanged(bool checked)
3767 m_settings->normalizationFilterEnabled(checked);
3768 normalizationDynamicChanged(ui->checkBoxNormalizationFilterDynamic->isChecked());
3772 * Dynamic normalization enabled changed
3774 void MainWindow::normalizationDynamicChanged(bool checked)
3776 ui->spinBoxNormalizationFilterSize->setEnabled(ui->checkBoxNormalizationFilterEnabled->isChecked() && checked);
3777 m_settings->normalizationFilterDynamic(checked);
3781 * Normalization max. volume changed
3783 void MainWindow::normalizationMaxVolumeChanged(double value)
3785 m_settings->normalizationFilterMaxVolume(static_cast<int>(value * 100.0));
3789 * Normalization equalization mode changed
3791 void MainWindow::normalizationCoupledChanged(bool checked)
3793 m_settings->normalizationFilterCoupled(checked);
3797 * Normalization filter size changed
3799 void MainWindow::normalizationFilterSizeChanged(int value)
3801 m_settings->normalizationFilterSize(value);
3805 * Normalization filter size editing finished
3807 void MainWindow::normalizationFilterSizeFinished(void)
3809 const int value = ui->spinBoxNormalizationFilterSize->value();
3810 if((value % 2) != 1)
3812 bool rnd = MUtils::parity(MUtils::next_rand32());
3813 ui->spinBoxNormalizationFilterSize->setValue(rnd ? value+1 : value-1);
3818 * Tone adjustment has changed (Bass)
3820 void MainWindow::toneAdjustBassChanged(double value)
3822 m_settings->toneAdjustBass(static_cast<int>(value * 100.0));
3823 ui->spinBoxToneAdjustBass->setPrefix((value > 0) ? "+" : QString());
3827 * Tone adjustment has changed (Treble)
3829 void MainWindow::toneAdjustTrebleChanged(double value)
3831 m_settings->toneAdjustTreble(static_cast<int>(value * 100.0));
3832 ui->spinBoxToneAdjustTreble->setPrefix((value > 0) ? "+" : QString());
3836 * Tone adjustment has been reset
3838 void MainWindow::toneAdjustTrebleReset(void)
3840 ui->spinBoxToneAdjustBass->setValue(m_settings->toneAdjustBassDefault());
3841 ui->spinBoxToneAdjustTreble->setValue(m_settings->toneAdjustTrebleDefault());
3842 toneAdjustBassChanged(ui->spinBoxToneAdjustBass->value());
3843 toneAdjustTrebleChanged(ui->spinBoxToneAdjustTreble->value());
3847 * Custom encoder parameters changed
3849 void MainWindow::customParamsChanged(void)
3851 ui->lineEditCustomParamLAME->setText(ui->lineEditCustomParamLAME->text().simplified());
3852 ui->lineEditCustomParamOggEnc->setText(ui->lineEditCustomParamOggEnc->text().simplified());
3853 ui->lineEditCustomParamNeroAAC->setText(ui->lineEditCustomParamNeroAAC->text().simplified());
3854 ui->lineEditCustomParamFLAC->setText(ui->lineEditCustomParamFLAC->text().simplified());
3855 ui->lineEditCustomParamAften->setText(ui->lineEditCustomParamAften->text().simplified());
3856 ui->lineEditCustomParamOpus->setText(ui->lineEditCustomParamOpus->text().simplified());
3858 bool customParamsUsed = false;
3859 if(!ui->lineEditCustomParamLAME->text().isEmpty()) customParamsUsed = true;
3860 if(!ui->lineEditCustomParamOggEnc->text().isEmpty()) customParamsUsed = true;
3861 if(!ui->lineEditCustomParamNeroAAC->text().isEmpty()) customParamsUsed = true;
3862 if(!ui->lineEditCustomParamFLAC->text().isEmpty()) customParamsUsed = true;
3863 if(!ui->lineEditCustomParamAften->text().isEmpty()) customParamsUsed = true;
3864 if(!ui->lineEditCustomParamOpus->text().isEmpty()) customParamsUsed = true;
3866 ui->labelCustomParamsIcon->setVisible(customParamsUsed);
3867 ui->labelCustomParamsText->setVisible(customParamsUsed);
3868 ui->labelCustomParamsSpacer->setVisible(customParamsUsed);
3870 EncoderRegistry::saveEncoderCustomParams(m_settings, SettingsModel::MP3Encoder, ui->lineEditCustomParamLAME->text());
3871 EncoderRegistry::saveEncoderCustomParams(m_settings, SettingsModel::VorbisEncoder, ui->lineEditCustomParamOggEnc->text());
3872 EncoderRegistry::saveEncoderCustomParams(m_settings, SettingsModel::AACEncoder, ui->lineEditCustomParamNeroAAC->text());
3873 EncoderRegistry::saveEncoderCustomParams(m_settings, SettingsModel::FLACEncoder, ui->lineEditCustomParamFLAC->text());
3874 EncoderRegistry::saveEncoderCustomParams(m_settings, SettingsModel::AC3Encoder, ui->lineEditCustomParamAften->text());
3875 EncoderRegistry::saveEncoderCustomParams(m_settings, SettingsModel::OpusEncoder, ui->lineEditCustomParamOpus->text());
3879 * One of the rename buttons has been clicked
3881 void MainWindow::renameButtonClicked(bool checked)
3883 if(QPushButton *const button = dynamic_cast<QPushButton*>(QObject::sender()))
3885 QWidget *pages[] = { ui->pageRename_Rename, ui->pageRename_RegExp, ui->pageRename_FileEx };
3886 QPushButton *buttons[] = { ui->buttonRename_Rename, ui->buttonRename_RegExp, ui->buttonRename_FileEx };
3887 for(int i = 0; i < 3; i++)
3889 const bool match = (button == buttons[i]);
3890 buttons[i]->setChecked(match);
3891 if(match && checked) ui->stackedWidget->setCurrentWidget(pages[i]);
3897 * Rename output files enabled changed
3899 void MainWindow::renameOutputEnabledChanged(const bool &checked)
3901 m_settings->renameFiles_renameEnabled(checked);
3905 * Rename output files patterm changed
3907 void MainWindow::renameOutputPatternChanged(void)
3909 QString temp = ui->lineEditRenamePattern->text().simplified();
3910 ui->lineEditRenamePattern->setText(temp.isEmpty() ? m_settings->renameFiles_renamePatternDefault() : temp);
3911 m_settings->renameFiles_renamePattern(ui->lineEditRenamePattern->text());
3915 * Rename output files patterm changed
3917 void MainWindow::renameOutputPatternChanged(const QString &text, const bool &silent)
3919 QString pattern(text.simplified());
3921 pattern.replace("<BaseName>", "The_White_Stripes_-_Fell_In_Love_With_A_Girl", Qt::CaseInsensitive);
3922 pattern.replace("<TrackNo>", "04", Qt::CaseInsensitive);
3923 pattern.replace("<Title>", "Fell In Love With A Girl", Qt::CaseInsensitive);
3924 pattern.replace("<Artist>", "The White Stripes", Qt::CaseInsensitive);
3925 pattern.replace("<Album>", "White Blood Cells", Qt::CaseInsensitive);
3926 pattern.replace("<Year>", "2001", Qt::CaseInsensitive);
3927 pattern.replace("<Comment>", "Encoded by LameXP", Qt::CaseInsensitive);
3929 const QString patternClean = MUtils::clean_file_name(pattern);
3931 if(pattern.compare(patternClean))
3933 if(ui->lineEditRenamePattern->palette().color(QPalette::Text) != Qt::red)
3935 if(!silent) MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
3936 SET_TEXT_COLOR(ui->lineEditRenamePattern, Qt::red);
3939 else
3941 if(ui->lineEditRenamePattern->palette() != QPalette())
3943 if(!silent) MUtils::Sound::beep(MUtils::Sound::BEEP_NFO);
3944 ui->lineEditRenamePattern->setPalette(QPalette());
3948 ui->labelRanameExample->setText(patternClean);
3952 * Regular expression enabled changed
3954 void MainWindow::renameRegExpEnabledChanged(const bool &checked)
3956 m_settings->renameFiles_regExpEnabled(checked);
3960 * Regular expression value has changed
3962 void MainWindow::renameRegExpValueChanged(void)
3964 const QString search = ui->lineEditRenameRegExp_Search->text() .trimmed();
3965 const QString replace = ui->lineEditRenameRegExp_Replace->text().simplified();
3966 ui->lineEditRenameRegExp_Search ->setText(search.isEmpty() ? m_settings->renameFiles_regExpSearchDefault() : search);
3967 ui->lineEditRenameRegExp_Replace->setText(replace.isEmpty() ? m_settings->renameFiles_regExpReplaceDefault() : replace);
3968 m_settings->renameFiles_regExpSearch (ui->lineEditRenameRegExp_Search ->text());
3969 m_settings->renameFiles_regExpReplace(ui->lineEditRenameRegExp_Replace->text());
3973 * Regular expression search pattern has changed
3975 void MainWindow::renameRegExpSearchChanged(const QString &text, const bool &silent)
3977 const QString pattern(text.trimmed());
3979 if((!pattern.isEmpty()) && (!QRegExp(pattern.trimmed()).isValid()))
3981 if(ui->lineEditRenameRegExp_Search->palette().color(QPalette::Text) != Qt::red)
3983 if(!silent) MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
3984 SET_TEXT_COLOR(ui->lineEditRenameRegExp_Search, Qt::red);
3987 else
3989 if(ui->lineEditRenameRegExp_Search->palette() != QPalette())
3991 if(!silent) MUtils::Sound::beep(MUtils::Sound::BEEP_NFO);
3992 ui->lineEditRenameRegExp_Search->setPalette(QPalette());
3996 renameRegExpReplaceChanged(ui->lineEditRenameRegExp_Replace->text(), silent);
4000 * Regular expression replacement string changed
4002 void MainWindow::renameRegExpReplaceChanged(const QString &text, const bool &silent)
4004 QString replacement(text.simplified());
4005 const QString search(ui->lineEditRenameRegExp_Search->text().trimmed());
4007 if(!search.isEmpty())
4009 const QRegExp regexp(search);
4010 if(regexp.isValid())
4012 const int count = regexp.captureCount();
4013 const QString blank;
4014 for(int i = 0; i < count; i++)
4016 replacement.replace(QString("\\%0").arg(QString::number(i+1)), blank);
4021 if(replacement.compare(MUtils::clean_file_name(replacement)))
4023 if(ui->lineEditRenameRegExp_Replace->palette().color(QPalette::Text) != Qt::red)
4025 if(!silent) MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
4026 SET_TEXT_COLOR(ui->lineEditRenameRegExp_Replace, Qt::red);
4029 else
4031 if(ui->lineEditRenameRegExp_Replace->palette() != QPalette())
4033 if(!silent) MUtils::Sound::beep(MUtils::Sound::BEEP_NFO);
4034 ui->lineEditRenameRegExp_Replace->setPalette(QPalette());
4040 * Show list of rename macros
4042 void MainWindow::showRenameMacros(const QString &text)
4044 if(text.compare("reset", Qt::CaseInsensitive) == 0)
4046 ui->lineEditRenamePattern->setText(m_settings->renameFiles_renamePatternDefault());
4047 return;
4050 if(text.compare("regexp", Qt::CaseInsensitive) == 0)
4052 MUtils::OS::shell_open(this, "http://www.regular-expressions.info/quickstart.html");
4053 return;
4056 const QString format = QString("<tr><td><tt>&lt;%1&gt;</tt></td><td>&nbsp;&nbsp;</td><td>%2</td></tr>");
4058 QString message = QString("<table>");
4059 message += QString(format).arg("BaseName", tr("File name without extension"));
4060 message += QString(format).arg("TrackNo", tr("Track number with leading zero"));
4061 message += QString(format).arg("Title", tr("Track title"));
4062 message += QString(format).arg("Artist", tr("Artist name"));
4063 message += QString(format).arg("Album", tr("Album name"));
4064 message += QString(format).arg("Year", tr("Year with (at least) four digits"));
4065 message += QString(format).arg("Comment", tr("Comment"));
4066 message += "</table><br><br>";
4067 message += QString("%1<br>").arg(tr("Characters forbidden in file names:"));
4068 message += "<b><tt>\\ / : * ? &lt; &gt; |<br>";
4070 QMessageBox::information(this, tr("Rename Macros"), message, tr("Discard"));
4073 void MainWindow::forceStereoDownmixEnabledChanged(bool checked)
4075 m_settings->forceStereoDownmix(checked);
4079 * Maximum number of instances changed
4081 void MainWindow::updateMaximumInstances(int value)
4083 ui->labelMaxInstances->setText(tr("%n Instance(s)", "", value));
4084 m_settings->maximumInstances(ui->checkBoxAutoDetectInstances->isChecked() ? NULL : value);
4088 * Auto-detect number of instances
4090 void MainWindow::autoDetectInstancesChanged(bool checked)
4092 m_settings->maximumInstances(checked ? NULL : ui->sliderMaxInstances->value());
4096 * Browse for custom TEMP folder button clicked
4098 void MainWindow::browseCustomTempFolderButtonClicked(void)
4100 QString newTempFolder;
4102 if(MUtils::GUI::themes_enabled())
4104 newTempFolder = QFileDialog::getExistingDirectory(this, QString(), m_settings->customTempPath());
4106 else
4108 QFileDialog dialog(this);
4109 dialog.setFileMode(QFileDialog::DirectoryOnly);
4110 dialog.setDirectory(m_settings->customTempPath());
4111 if(dialog.exec())
4113 newTempFolder = dialog.selectedFiles().first();
4117 if(!newTempFolder.isEmpty())
4119 QFile writeTest(QString("%1/~%2.tmp").arg(newTempFolder, MUtils::rand_str()));
4120 if(writeTest.open(QIODevice::ReadWrite))
4122 writeTest.remove();
4123 ui->lineEditCustomTempFolder->setText(QDir::toNativeSeparators(newTempFolder));
4125 else
4127 QMessageBox::warning(this, tr("Access Denied"), tr("Cannot write to the selected directory. Please choose another directory!"));
4133 * Custom TEMP folder changed
4135 void MainWindow::customTempFolderChanged(const QString &text)
4137 m_settings->customTempPath(QDir::fromNativeSeparators(text));
4141 * Use custom TEMP folder option changed
4143 void MainWindow::useCustomTempFolderChanged(bool checked)
4145 m_settings->customTempPathEnabled(!checked);
4149 * Help for custom parameters was requested
4151 void MainWindow::customParamsHelpRequested(QWidget *obj, QEvent *event)
4153 if(event->type() != QEvent::MouseButtonRelease)
4155 return;
4158 if(QMouseEvent *mouseEvent = dynamic_cast<QMouseEvent*>(event))
4160 QPoint pos = mouseEvent->pos();
4161 if(!(pos.x() <= obj->width() && pos.y() <= obj->height() && pos.x() >= 0 && pos.y() >= 0 && mouseEvent->button() != Qt::MidButton))
4163 return;
4167 if(obj == ui->helpCustomParamLAME) showCustomParamsHelpScreen("lame.exe", "--longhelp");
4168 else if(obj == ui->helpCustomParamOggEnc) showCustomParamsHelpScreen("oggenc2.exe", "--help");
4169 else if(obj == ui->helpCustomParamNeroAAC)
4171 switch(EncoderRegistry::getAacEncoder())
4173 case SettingsModel::AAC_ENCODER_QAAC: showCustomParamsHelpScreen("qaac.exe", "--help"); break;
4174 case SettingsModel::AAC_ENCODER_FHG : showCustomParamsHelpScreen("fhgaacenc.exe", "" ); break;
4175 case SettingsModel::AAC_ENCODER_FDK : showCustomParamsHelpScreen("fdkaac.exe", "--help"); break;
4176 case SettingsModel::AAC_ENCODER_NERO: showCustomParamsHelpScreen("neroAacEnc.exe", "-help" ); break;
4177 default: MUtils::Sound::beep(MUtils::Sound::BEEP_ERR); break;
4180 else if(obj == ui->helpCustomParamFLAC) showCustomParamsHelpScreen("flac.exe", "--help");
4181 else if(obj == ui->helpCustomParamAften) showCustomParamsHelpScreen("aften.exe", "-h" );
4182 else if(obj == ui->helpCustomParamOpus) showCustomParamsHelpScreen("opusenc.exe", "--help");
4183 else MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
4187 * Show help for custom parameters
4189 void MainWindow::showCustomParamsHelpScreen(const QString &toolName, const QString &command)
4191 const QString binary = lamexp_tools_lookup(toolName);
4192 if(binary.isEmpty())
4194 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
4195 qWarning("customParamsHelpRequested: Binary could not be found!");
4196 return;
4199 QProcess process;
4200 MUtils::init_process(process, QFileInfo(binary).absolutePath());
4202 process.start(binary, command.isEmpty() ? QStringList() : QStringList() << command);
4204 qApp->setOverrideCursor(QCursor(Qt::WaitCursor));
4206 if(process.waitForStarted(15000))
4208 qApp->processEvents();
4209 process.waitForFinished(15000);
4212 if(process.state() != QProcess::NotRunning)
4214 process.kill();
4215 process.waitForFinished(-1);
4218 qApp->restoreOverrideCursor();
4219 QStringList output; bool spaceFlag = true;
4221 while(process.canReadLine())
4223 QString temp = QString::fromUtf8(process.readLine());
4224 TRIM_STRING_RIGHT(temp);
4225 if(temp.isEmpty())
4227 if(!spaceFlag) { output << temp; spaceFlag = true; }
4229 else
4231 output << temp; spaceFlag = false;
4235 if(output.count() < 1)
4237 qWarning("Empty output, cannot show help screen!");
4238 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
4241 LogViewDialog *dialog = new LogViewDialog(this);
4242 TEMP_HIDE_DROPBOX( dialog->exec(output); );
4243 MUTILS_DELETE(dialog);
4246 void MainWindow::overwriteModeChanged(int id)
4248 if((id == SettingsModel::Overwrite_Replaces) && (m_settings->overwriteMode() != SettingsModel::Overwrite_Replaces))
4250 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)
4252 ui->radioButtonOverwriteModeKeepBoth->setChecked(m_settings->overwriteMode() == SettingsModel::Overwrite_KeepBoth);
4253 ui->radioButtonOverwriteModeSkipFile->setChecked(m_settings->overwriteMode() == SettingsModel::Overwrite_SkipFile);
4254 return;
4258 m_settings->overwriteMode(id);
4262 * Reset all advanced options to their defaults
4264 void MainWindow::resetAdvancedOptionsButtonClicked(void)
4266 PLAY_SOUND_OPTIONAL("blast", true);
4268 ui->sliderLameAlgoQuality ->setValue(m_settings->lameAlgoQualityDefault());
4269 ui->spinBoxBitrateManagementMin ->setValue(m_settings->bitrateManagementMinRateDefault());
4270 ui->spinBoxBitrateManagementMax ->setValue(m_settings->bitrateManagementMaxRateDefault());
4271 ui->spinBoxNormalizationFilterPeak->setValue(static_cast<double>(m_settings->normalizationFilterMaxVolumeDefault()) / 100.0);
4272 ui->spinBoxNormalizationFilterSize->setValue(m_settings->normalizationFilterSizeDefault());
4273 ui->spinBoxToneAdjustBass ->setValue(static_cast<double>(m_settings->toneAdjustBassDefault()) / 100.0);
4274 ui->spinBoxToneAdjustTreble ->setValue(static_cast<double>(m_settings->toneAdjustTrebleDefault()) / 100.0);
4275 ui->spinBoxAftenSearchSize ->setValue(m_settings->aftenExponentSearchSizeDefault());
4276 ui->spinBoxOpusComplexity ->setValue(m_settings->opusComplexityDefault());
4277 ui->comboBoxMP3ChannelMode ->setCurrentIndex(m_settings->lameChannelModeDefault());
4278 ui->comboBoxSamplingRate ->setCurrentIndex(m_settings->samplingRateDefault());
4279 ui->comboBoxAACProfile ->setCurrentIndex(m_settings->aacEncProfileDefault());
4280 ui->comboBoxAftenCodingMode ->setCurrentIndex(m_settings->aftenAudioCodingModeDefault());
4281 ui->comboBoxAftenDRCMode ->setCurrentIndex(m_settings->aftenDynamicRangeCompressionDefault());
4282 ui->comboBoxOpusFramesize ->setCurrentIndex(m_settings->opusFramesizeDefault());
4284 SET_CHECKBOX_STATE(ui->checkBoxBitrateManagement, m_settings->bitrateManagementEnabledDefault());
4285 SET_CHECKBOX_STATE(ui->checkBoxNeroAAC2PassMode, m_settings->neroAACEnable2PassDefault());
4286 SET_CHECKBOX_STATE(ui->checkBoxNormalizationFilterEnabled, m_settings->normalizationFilterEnabledDefault());
4287 SET_CHECKBOX_STATE(ui->checkBoxNormalizationFilterDynamic, m_settings->normalizationFilterDynamicDefault());
4288 SET_CHECKBOX_STATE(ui->checkBoxNormalizationFilterCoupled, m_settings->normalizationFilterCoupledDefault());
4289 SET_CHECKBOX_STATE(ui->checkBoxAutoDetectInstances, (m_settings->maximumInstancesDefault() < 1));
4290 SET_CHECKBOX_STATE(ui->checkBoxUseSystemTempFolder, (!m_settings->customTempPathEnabledDefault()));
4291 SET_CHECKBOX_STATE(ui->checkBoxAftenFastAllocation, m_settings->aftenFastBitAllocationDefault());
4292 SET_CHECKBOX_STATE(ui->checkBoxRename_Rename, m_settings->renameFiles_renameEnabledDefault());
4293 SET_CHECKBOX_STATE(ui->checkBoxRename_RegExp, m_settings->renameFiles_regExpEnabledDefault());
4294 SET_CHECKBOX_STATE(ui->checkBoxForceStereoDownmix, m_settings->forceStereoDownmixDefault());
4295 SET_CHECKBOX_STATE(ui->checkBoxOpusDisableResample, m_settings->opusDisableResampleDefault());
4297 ui->lineEditCustomParamLAME ->setText(m_settings->customParametersLAMEDefault());
4298 ui->lineEditCustomParamOggEnc ->setText(m_settings->customParametersOggEncDefault());
4299 ui->lineEditCustomParamNeroAAC ->setText(m_settings->customParametersAacEncDefault());
4300 ui->lineEditCustomParamFLAC ->setText(m_settings->customParametersFLACDefault());
4301 ui->lineEditCustomParamOpus ->setText(m_settings->customParametersOpusEncDefault());
4302 ui->lineEditCustomTempFolder ->setText(QDir::toNativeSeparators(m_settings->customTempPathDefault()));
4303 ui->lineEditRenamePattern ->setText(m_settings->renameFiles_renamePatternDefault());
4304 ui->lineEditRenameRegExp_Search ->setText(m_settings->renameFiles_regExpSearchDefault());
4305 ui->lineEditRenameRegExp_Replace->setText(m_settings->renameFiles_regExpReplaceDefault());
4307 if(m_settings->overwriteModeDefault() == SettingsModel::Overwrite_KeepBoth) ui->radioButtonOverwriteModeKeepBoth->click();
4308 if(m_settings->overwriteModeDefault() == SettingsModel::Overwrite_SkipFile) ui->radioButtonOverwriteModeSkipFile->click();
4309 if(m_settings->overwriteModeDefault() == SettingsModel::Overwrite_Replaces) ui->radioButtonOverwriteModeReplaces->click();
4311 ui->scrollArea->verticalScrollBar()->setValue(0);
4312 ui->buttonRename_Rename->click();
4313 customParamsChanged();
4314 renameOutputPatternChanged();
4315 renameRegExpValueChanged();
4318 // =========================================================
4319 // Multi-instance handling slots
4320 // =========================================================
4323 * Other instance detected
4325 void MainWindow::notifyOtherInstance(void)
4327 if(!(BANNER_VISIBLE))
4329 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);
4330 msgBox.exec();
4335 * Add file from another instance
4337 void MainWindow::addFileDelayed(const QString &filePath, bool tryASAP)
4339 if(tryASAP && !m_delayedFileTimer->isActive())
4341 qDebug("Received file: %s", MUTILS_UTF8(filePath));
4342 m_delayedFileList->append(filePath);
4343 QTimer::singleShot(0, this, SLOT(handleDelayedFiles()));
4346 m_delayedFileTimer->stop();
4347 qDebug("Received file: %s", MUTILS_UTF8(filePath));
4348 m_delayedFileList->append(filePath);
4349 m_delayedFileTimer->start(5000);
4353 * Add files from another instance
4355 void MainWindow::addFilesDelayed(const QStringList &filePaths, bool tryASAP)
4357 if(tryASAP && (!m_delayedFileTimer->isActive()))
4359 qDebug("Received %d file(s).", filePaths.count());
4360 m_delayedFileList->append(filePaths);
4361 QTimer::singleShot(0, this, SLOT(handleDelayedFiles()));
4363 else
4365 m_delayedFileTimer->stop();
4366 qDebug("Received %d file(s).", filePaths.count());
4367 m_delayedFileList->append(filePaths);
4368 m_delayedFileTimer->start(5000);
4373 * Add folder from another instance
4375 void MainWindow::addFolderDelayed(const QString &folderPath, bool recursive)
4377 if(!(BANNER_VISIBLE))
4379 addFolder(folderPath, recursive, true);
4383 // =========================================================
4384 // Misc slots
4385 // =========================================================
4388 * Restore the override cursor
4390 void MainWindow::restoreCursor(void)
4392 QApplication::restoreOverrideCursor();