OSDN Git Service

Added an option to disable to icon in the notification area.
[lamexp/LameXP.git] / src / Model_Settings.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2023 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; always including the non-optional
9 // LAMEXP GNU GENERAL PUBLIC LICENSE ADDENDUM. See "License.txt" file!
10 //
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.
15 //
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.
19 //
20 // http://www.gnu.org/licenses/gpl-2.0.txt
21 ///////////////////////////////////////////////////////////////////////////////
22
23 #include "Model_Settings.h"
24
25 //Internal
26 #include "Global.h"
27 #include "Registry_Encoder.h"
28
29 //MUtils
30 #include <MUtils/Global.h>
31 #include <MUtils/Translation.h>
32 #include <MUtils/OSSupport.h>
33
34 //Qt
35 #include <QSettings>
36 #include <QDesktopServices>
37 #include <QApplication>
38 #include <QString>
39 #include <QFileInfo>
40 #include <QDir>
41 #include <QStringList>
42 #include <QLocale>
43 #include <QRegExp>
44 #include <QReadWriteLock>
45 #include <QReadLocker>
46 #include <QWriteLocker>
47 #include <QHash>
48 #include <QMutex>
49 #include <QSet>
50
51 ////////////////////////////////////////////////////////////
52 // SettingsCache Class
53 ////////////////////////////////////////////////////////////
54
55 class SettingsCache
56 {
57 public:
58         SettingsCache(QSettings *const configFile)
59         :
60                 m_configFile(configFile),
61                 m_cache(new cache_data_t()),
62                 m_cacheDirty(new string_set_t())
63         {
64         }
65
66         ~SettingsCache(void)
67         {
68                 flushValues();
69         }
70
71         inline void storeValue(const QString &key, const QVariant &value)
72         {
73                 QWriteLocker writeLock(&m_cacheLock);
74         
75                 if(!m_cache->contains(key))
76                 {
77                         m_cache->insert(key, value);
78                         m_cacheDirty->insert(key);
79                 }
80                 else
81                 {
82                         if(m_cache->value(key) != value)
83                         {
84                                 m_cache->insert(key, value);
85                                 m_cacheDirty->insert(key);
86                         }
87                 }
88         }
89
90         inline QVariant loadValue(const QString &key, const QVariant &defaultValue) const
91         {
92                 QReadLocker readLock(&m_cacheLock);
93
94                 if(m_cache->contains(key))
95                 {
96                         return m_cache->value(key, defaultValue);
97                 }
98
99                 readLock.unlock();
100                 QWriteLocker writeLock(&m_cacheLock);
101
102                 if(!m_cache->contains(key))
103                 {
104                         const QVariant storedValue = m_configFile->value(key, defaultValue);
105                         m_cache->insert(key, storedValue);
106                 }
107
108                 return m_cache->value(key, defaultValue);
109         }
110
111         inline void flushValues(void)
112         {
113                 QWriteLocker writeLock(&m_cacheLock);
114
115                 if(!m_cacheDirty->isEmpty())
116                 {
117                         QSet<QString>::ConstIterator iter;
118                         for(iter = m_cacheDirty->constBegin(); iter != m_cacheDirty->constEnd(); iter++)
119                         {
120                                 if(m_cache->contains(*iter))
121                                 {
122                                         m_configFile->setValue((*iter), m_cache->value(*iter));
123                                 }
124                                 else
125                                 {
126                                         qWarning("Could not find '%s' in cache, but it has been marked as dirty!", MUTILS_UTF8(*iter));
127                                 }
128                         }
129                         m_configFile->sync();
130                         m_cacheDirty->clear();
131                 }
132         }
133
134 private:
135         typedef QSet<QString>            string_set_t;
136         typedef QHash<QString, QVariant> cache_data_t;
137
138         QScopedPointer<QSettings>    m_configFile;
139         QScopedPointer<cache_data_t> m_cache;
140         QScopedPointer<string_set_t> m_cacheDirty;
141         
142         mutable QReadWriteLock m_cacheLock;
143 };
144
145 ////////////////////////////////////////////////////////////
146 // Macros
147 ////////////////////////////////////////////////////////////
148
149 #define LAMEXP_MAKE_OPTION_I(OPT,DEF) \
150 qint32 SettingsModel::OPT(void) const { return m_configCache->loadValue(g_settingsId_##OPT, (DEF)).toInt(); } \
151 void SettingsModel::OPT(const qint32 &value) { m_configCache->storeValue(g_settingsId_##OPT, value); } \
152 qint32 SettingsModel::OPT##Default(void) { return (DEF); }
153
154 #define LAMEXP_MAKE_OPTION_S(OPT,DEF) \
155 QString SettingsModel::OPT(void) const { return m_configCache->loadValue(g_settingsId_##OPT, (DEF)).toString().trimmed(); } \
156 void SettingsModel::OPT(const QString &value) { m_configCache->storeValue(g_settingsId_##OPT, value); } \
157 QString SettingsModel::OPT##Default(void) { return (DEF); }
158
159 #define LAMEXP_MAKE_OPTION_B(OPT,DEF) \
160 bool SettingsModel::OPT(void) const { return m_configCache->loadValue(g_settingsId_##OPT, (DEF)).toBool(); } \
161 void SettingsModel::OPT(bool value) { m_configCache->storeValue(g_settingsId_##OPT, value); } \
162 bool SettingsModel::OPT##Default(void) { return (DEF); }
163
164 #define LAMEXP_MAKE_OPTION_U(OPT,DEF) \
165 quint32 SettingsModel::OPT(void) const { return m_configCache->loadValue(g_settingsId_##OPT, (DEF)).toUInt(); } \
166 void SettingsModel::OPT(const quint32 &value) { m_configCache->storeValue(g_settingsId_##OPT, value); } \
167 quint32 SettingsModel::OPT##Default(void) { return (DEF); }
168
169 #define LAMEXP_MAKE_ID(DEC,STR) static const char *g_settingsId_##DEC = STR
170
171 #define REMOVE_GROUP(OBJ,ID) do \
172 { \
173         OBJ->beginGroup(ID); \
174         OBJ->remove(""); \
175         OBJ->endGroup(); \
176 } \
177 while(0)
178
179 ////////////////////////////////////////////////////////////
180 // Utility functions
181 ////////////////////////////////////////////////////////////
182
183 static bool dir_exists(const QString &path)
184 {
185         const QFileInfo info(path);
186         return info.exists() && info.isDir();
187 }
188
189 static QString find_existing_ancestor(const QString &path)
190 {
191         for (QString parentPath = path; !parentPath.isEmpty(); parentPath = MUtils::parent_path(parentPath))
192         {
193                 if (dir_exists(parentPath))
194                 {
195                         return parentPath; /*existing parent found*/
196                 }
197         }
198         return QString();
199 }
200
201 ////////////////////////////////////////////////////////////
202 // Constants
203 ////////////////////////////////////////////////////////////
204
205 //Setting ID's
206 LAMEXP_MAKE_ID(aacEncProfile,                "AdvancedOptions/AACEnc/ForceProfile");
207 LAMEXP_MAKE_ID(aftenAudioCodingMode,         "AdvancedOptions/Aften/AudioCodingMode");
208 LAMEXP_MAKE_ID(aftenDynamicRangeCompression, "AdvancedOptions/Aften/DynamicRangeCompression");
209 LAMEXP_MAKE_ID(aftenExponentSearchSize,      "AdvancedOptions/Aften/ExponentSearchSize");
210 LAMEXP_MAKE_ID(aftenFastBitAllocation,       "AdvancedOptions/Aften/FastBitAllocation");
211 LAMEXP_MAKE_ID(antivirNotificationsEnabled,  "Flags/EnableAntivirusNotifications");
212 LAMEXP_MAKE_ID(autoUpdateCheckBeta,          "AutoUpdate/CheckForBetaVersions");
213 LAMEXP_MAKE_ID(autoUpdateEnabled,            "AutoUpdate/Enabled");
214 LAMEXP_MAKE_ID(autoUpdateLastCheck,          "AutoUpdate/LastCheck");
215 LAMEXP_MAKE_ID(bitrateManagementEnabled,     "AdvancedOptions/BitrateManagement/Enabled");
216 LAMEXP_MAKE_ID(bitrateManagementMaxRate,     "AdvancedOptions/BitrateManagement/MaxRate");
217 LAMEXP_MAKE_ID(bitrateManagementMinRate,     "AdvancedOptions/BitrateManagement/MinRate");
218 LAMEXP_MAKE_ID(compressionAbrBitrateAacEnc,  "Compression/AbrTaretBitrate/AacEnc");
219 LAMEXP_MAKE_ID(compressionAbrBitrateAften,   "Compression/AbrTaretBitrate/Aften");
220 LAMEXP_MAKE_ID(compressionAbrBitrateDcaEnc,  "Compression/AbrTaretBitrate/DcaEnc");
221 LAMEXP_MAKE_ID(compressionAbrBitrateFLAC,    "Compression/AbrTaretBitrate/FLAC");
222 LAMEXP_MAKE_ID(compressionAbrBitrateLAME,    "Compression/AbrTaretBitrate/LAME");
223 LAMEXP_MAKE_ID(compressionAbrBitrateMacEnc,  "Compression/AbrTaretBitrate/MacEnc");
224 LAMEXP_MAKE_ID(compressionAbrBitrateOggEnc,  "Compression/AbrTaretBitrate/OggEnc");
225 LAMEXP_MAKE_ID(compressionAbrBitrateOpusEnc, "Compression/AbrTaretBitrate/OpusEnc");
226 LAMEXP_MAKE_ID(compressionAbrBitrateWave,    "Compression/AbrTaretBitrate/Wave");
227 LAMEXP_MAKE_ID(compressionCbrBitrateAacEnc,  "Compression/CbrTaretBitrate/AacEnc");
228 LAMEXP_MAKE_ID(compressionCbrBitrateAften,   "Compression/CbrTaretBitrate/Aften");
229 LAMEXP_MAKE_ID(compressionCbrBitrateDcaEnc,  "Compression/CbrTaretBitrate/DcaEnc");
230 LAMEXP_MAKE_ID(compressionCbrBitrateFLAC,    "Compression/CbrTaretBitrate/FLAC");
231 LAMEXP_MAKE_ID(compressionCbrBitrateLAME,    "Compression/CbrTaretBitrate/LAME");
232 LAMEXP_MAKE_ID(compressionCbrBitrateMacEnc,  "Compression/CbrTaretBitrate/MacEnc");
233 LAMEXP_MAKE_ID(compressionCbrBitrateOggEnc,  "Compression/CbrTaretBitrate/OggEnc");
234 LAMEXP_MAKE_ID(compressionCbrBitrateOpusEnc, "Compression/CbrTaretBitrate/OpusEnc");
235 LAMEXP_MAKE_ID(compressionCbrBitrateWave,    "Compression/CbrTaretBitrate/Wave");
236 LAMEXP_MAKE_ID(compressionEncoder,           "Compression/Encoder");
237 LAMEXP_MAKE_ID(compressionRCModeAacEnc,      "Compression/RCMode/AacEnc");
238 LAMEXP_MAKE_ID(compressionRCModeAften,       "Compression/RCMode/Aften");
239 LAMEXP_MAKE_ID(compressionRCModeDcaEnc,      "Compression/RCMode/DcaEnc");
240 LAMEXP_MAKE_ID(compressionRCModeFLAC,        "Compression/RCMode/FLAC");
241 LAMEXP_MAKE_ID(compressionRCModeLAME,        "Compression/RCMode/LAME");
242 LAMEXP_MAKE_ID(compressionRCModeMacEnc,      "Compression/RCMode/MacEnc");
243 LAMEXP_MAKE_ID(compressionRCModeOggEnc,      "Compression/RCMode/OggEnc");
244 LAMEXP_MAKE_ID(compressionRCModeOpusEnc,     "Compression/RCMode/OpusEnc");
245 LAMEXP_MAKE_ID(compressionRCModeWave,        "Compression/RCMode/Wave");
246 LAMEXP_MAKE_ID(compressionVbrQualityAacEnc,  "Compression/VbrQualityLevel/AacEnc");
247 LAMEXP_MAKE_ID(compressionVbrQualityAften,   "Compression/VbrQualityLevel/Aften");
248 LAMEXP_MAKE_ID(compressionVbrQualityDcaEnc,  "Compression/VbrQualityLevel/DcaEnc");
249 LAMEXP_MAKE_ID(compressionVbrQualityFLAC,    "Compression/VbrQualityLevel/FLAC");
250 LAMEXP_MAKE_ID(compressionVbrQualityLAME,    "Compression/VbrQualityLevel/LAME");
251 LAMEXP_MAKE_ID(compressionVbrQualityMacEnc,  "Compression/VbrQualityLevel/MacEnc");
252 LAMEXP_MAKE_ID(compressionVbrQualityOggEnc,  "Compression/VbrQualityLevel/OggEnc");
253 LAMEXP_MAKE_ID(compressionVbrQualityOpusEnc, "Compression/VbrQualityLevel/OpusEnc");
254 LAMEXP_MAKE_ID(compressionVbrQualityWave,    "Compression/VbrQualityLevel/Wave");
255 LAMEXP_MAKE_ID(createPlaylist,               "Flags/AutoCreatePlaylist");
256 LAMEXP_MAKE_ID(currentLanguage,              "Localization/Language");
257 LAMEXP_MAKE_ID(currentLanguageFile,          "Localization/UseQMFile");
258 LAMEXP_MAKE_ID(customParametersAacEnc,       "AdvancedOptions/CustomParameters/AacEnc");
259 LAMEXP_MAKE_ID(customParametersAften,        "AdvancedOptions/CustomParameters/Aften");
260 LAMEXP_MAKE_ID(customParametersDcaEnc,       "AdvancedOptions/CustomParameters/DcaEnc");
261 LAMEXP_MAKE_ID(customParametersFLAC,         "AdvancedOptions/CustomParameters/FLAC");
262 LAMEXP_MAKE_ID(customParametersLAME,         "AdvancedOptions/CustomParameters/LAME");
263 LAMEXP_MAKE_ID(customParametersMacEnc,       "AdvancedOptions/CustomParameters/MacEnc");
264 LAMEXP_MAKE_ID(customParametersOggEnc,       "AdvancedOptions/CustomParameters/OggEnc");
265 LAMEXP_MAKE_ID(customParametersOpusEnc,      "AdvancedOptions/CustomParameters/OpusEnc");
266 LAMEXP_MAKE_ID(customParametersWave,         "AdvancedOptions/CustomParameters/Wave");
267 LAMEXP_MAKE_ID(customTempPath,               "AdvancedOptions/TempDirectory/CustomPath");
268 LAMEXP_MAKE_ID(customTempPathEnabled,        "AdvancedOptions/TempDirectory/UseCustomPath");
269 LAMEXP_MAKE_ID(disableTrayIcon,              "Flags/DisableTrayIcon");
270 LAMEXP_MAKE_ID(dropBoxWidgetEnabled,         "DropBoxWidget/Enabled");
271 LAMEXP_MAKE_ID(dropBoxWidgetPositionX,       "DropBoxWidget/Position/X");
272 LAMEXP_MAKE_ID(dropBoxWidgetPositionY,       "DropBoxWidget/Position/Y");
273 LAMEXP_MAKE_ID(favoriteOutputFolders,        "OutputDirectory/Favorites");
274 LAMEXP_MAKE_ID(forceStereoDownmix,           "AdvancedOptions/StereoDownmix/Force");
275 LAMEXP_MAKE_ID(hibernateComputer,            "AdvancedOptions/HibernateComputerOnShutdown");
276 LAMEXP_MAKE_ID(interfaceStyle,               "InterfaceStyle");
277 LAMEXP_MAKE_ID(keepOriginalDataTime,         "AdvancedOptions/FileOperations/KeepOriginalDataTime");
278 LAMEXP_MAKE_ID(lameAlgoQuality,              "AdvancedOptions/LAME/AlgorithmQuality");
279 LAMEXP_MAKE_ID(lameChannelMode,              "AdvancedOptions/LAME/ChannelMode");
280 LAMEXP_MAKE_ID(licenseAccepted,              "LicenseAccepted");
281 LAMEXP_MAKE_ID(maximumInstances,             "AdvancedOptions/Threading/MaximumInstances");
282 LAMEXP_MAKE_ID(metaInfoPosition,             "MetaInformation/PlaylistPosition");
283 LAMEXP_MAKE_ID(mostRecentInputPath,          "InputDirectory/MostRecentPath");
284 LAMEXP_MAKE_ID(neroAACEnable2Pass,           "AdvancedOptions/AACEnc/Enable2Pass");
285 LAMEXP_MAKE_ID(neroAacNotificationsEnabled,  "Flags/EnableNeroAacNotifications");
286 LAMEXP_MAKE_ID(normalizationFilterEnabled,   "AdvancedOptions/VolumeNormalization/Enabled");
287 LAMEXP_MAKE_ID(normalizationFilterDynamic,   "AdvancedOptions/VolumeNormalization/UseDynAudNorm");
288 LAMEXP_MAKE_ID(normalizationFilterCoupled,   "AdvancedOptions/VolumeNormalization/ChannelCoupling");
289 LAMEXP_MAKE_ID(normalizationFilterMaxVolume, "AdvancedOptions/VolumeNormalization/MaxVolume");
290 LAMEXP_MAKE_ID(normalizationFilterSize,      "AdvancedOptions/VolumeNormalization/FilterLength");
291 LAMEXP_MAKE_ID(opusComplexity,               "AdvancedOptions/Opus/EncodingComplexity");
292 LAMEXP_MAKE_ID(opusDisableResample,          "AdvancedOptions/Opus/DisableResample");
293 LAMEXP_MAKE_ID(opusFramesize,                "AdvancedOptions/Opus/FrameSize");
294 LAMEXP_MAKE_ID(opusOptimizeFor,              "AdvancedOptions/Opus/OptimizeForSignalType");
295 LAMEXP_MAKE_ID(outputDir,                    "OutputDirectory/SelectedPath");
296 LAMEXP_MAKE_ID(outputToSourceDir,            "OutputDirectory/OutputToSourceFolder");
297 LAMEXP_MAKE_ID(overwriteMode,                "AdvancedOptions/FileOperations/OverwriteMode");
298 LAMEXP_MAKE_ID(prependRelativeSourcePath,    "OutputDirectory/PrependRelativeSourcePath");
299 LAMEXP_MAKE_ID(renameFiles_regExpEnabled,    "AdvancedOptions/RenameOutputFiles/RegExp/Enabled");
300 LAMEXP_MAKE_ID(renameFiles_regExpSearch,     "AdvancedOptions/RenameOutputFiles/RegExp/SearchPattern");
301 LAMEXP_MAKE_ID(renameFiles_regExpReplace,    "AdvancedOptions/RenameOutputFiles/RegExp/Replacement");
302 LAMEXP_MAKE_ID(renameFiles_renameEnabled,    "AdvancedOptions/RenameOutputFiles/Rename/Enabled");
303 LAMEXP_MAKE_ID(renameFiles_renamePattern,    "AdvancedOptions/RenameOutputFiles/Rename/Pattern");
304 LAMEXP_MAKE_ID(renameFiles_fileExtension,    "AdvancedOptions/RenameOutputFiles/FileExtensions/Overwrite");
305 LAMEXP_MAKE_ID(samplingRate,                 "AdvancedOptions/Common/Resampling");
306 LAMEXP_MAKE_ID(shellIntegrationEnabled,      "Flags/EnableShellIntegration");
307 LAMEXP_MAKE_ID(slowStartup,                  "Flags/SlowStartupDetected");
308 LAMEXP_MAKE_ID(soundsEnabled,                "Flags/EnableSounds");
309 LAMEXP_MAKE_ID(toneAdjustBass,               "AdvancedOptions/ToneAdjustment/Bass");
310 LAMEXP_MAKE_ID(toneAdjustTreble,             "AdvancedOptions/ToneAdjustment/Treble");
311 LAMEXP_MAKE_ID(versionNumber,                "VersionNumber");
312 LAMEXP_MAKE_ID(writeMetaTags,                "Flags/WriteMetaTags");
313
314 //LUT
315 const int SettingsModel::samplingRates[8] = {0, 16000, 22050, 24000, 32000, 44100, 48000, -1};
316
317 ////////////////////////////////////////////////////////////
318 // Constructor
319 ////////////////////////////////////////////////////////////
320
321 SettingsModel::SettingsModel(void)
322 :
323         m_configCache(NULL)
324 {
325         QString configPath = "LameXP.ini";
326         
327         if(!lamexp_version_portable())
328         {
329                 QString dataPath = initDirectory(QDesktopServices::storageLocation(QDesktopServices::DataLocation));
330                 if(!dataPath.isEmpty())
331                 {
332                         configPath = QString("%1/config.ini").arg(QDir(dataPath).canonicalPath());
333                 }
334                 else
335                 {
336                         qWarning("SettingsModel: DataLocation could not be initialized!");
337                         dataPath = initDirectory(QDesktopServices::storageLocation(QDesktopServices::HomeLocation));
338                         if(!dataPath.isEmpty())
339                         {
340                                 configPath = QString("%1/LameXP.ini").arg(QDir(dataPath).canonicalPath());
341                         }
342                 }
343         }
344         else
345         {
346                 qDebug("LameXP is running in \"portable\" mode -> config in application dir!\n");
347                 QString appPath = QFileInfo(QApplication::applicationFilePath()).canonicalFilePath();
348                 if(appPath.isEmpty())
349                 {
350                         appPath = QFileInfo(QApplication::applicationFilePath()).absoluteFilePath();
351                 }
352                 if(QFileInfo(appPath).exists() && QFileInfo(appPath).isFile())
353                 {
354                         configPath = QString("%1/%2.ini").arg(QFileInfo(appPath).absolutePath(), QFileInfo(appPath).completeBaseName());
355                 }
356         }
357
358         //Create settings
359         const QString groupKey = QString().sprintf("LameXP.%u", lamexp_version_confg());
360         QScopedPointer<QSettings> configFile(new QSettings(configPath, QSettings::IniFormat));
361         const QStringList childGroups = configFile->childGroups();
362
363         //Import legacy settings
364         if ((lamexp_version_confg() == 2188U) && (!childGroups.contains(groupKey, Qt::CaseInsensitive)))
365         {
366                 const char* const LEGACY_GROUPS[] = { "LameXP_41802188", "LameXP_41702188", NULL };
367                 for (size_t i = 0; LEGACY_GROUPS[i]; ++i)
368                 {
369                         const QString legacyGroupName = QString::fromLatin1(LEGACY_GROUPS[i]);
370                         if (childGroups.contains(legacyGroupName))
371                         {
372                                 qWarning("Importing legay settings: %s -> %s", MUTILS_UTF8(legacyGroupName), MUTILS_UTF8(groupKey));
373                                 configFile->beginGroup(legacyGroupName);
374                                 const QStringList existingKeys = configFile->allKeys();
375                                 configFile->endGroup();
376                                 for (QStringList::ConstIterator iter = existingKeys.constBegin(); iter != existingKeys.constEnd(); iter++)
377                                 {
378                                         configFile->setValue(QString("%1/%2").arg(groupKey, *iter), configFile->value(QString("%1/%2").arg(legacyGroupName, *iter)));
379                                 }
380                                 break;
381                         }
382                 }
383         }
384
385         //Clean-up settings
386         if (!childGroups.empty())
387         {
388                 static const int MAX_GROUPS = 5;
389                 QStringList obsoleteGroups;
390                 for (QStringList::ConstIterator iter = childGroups.constBegin(); iter != childGroups.constEnd(); iter++)
391                 {
392                         if (iter->compare(groupKey, Qt::CaseInsensitive) != 0)
393                         {
394                                 obsoleteGroups.append(*iter);
395                         }
396                 }
397                 if (obsoleteGroups.count() > MAX_GROUPS)
398                 {
399                         qSort(obsoleteGroups);
400                         for (int i = 0; i < MAX_GROUPS; i++)
401                         {
402                                 obsoleteGroups.removeLast();
403                         }
404                         for (QStringList::ConstIterator iter = obsoleteGroups.constBegin(); iter != obsoleteGroups.constEnd(); iter++)
405                         {
406                                 qWarning("Deleting obsolete group from config: %s", MUTILS_UTF8(*iter));
407                                 REMOVE_GROUP(configFile, (*iter));
408                         }
409                 }
410         }
411
412         //Setup settings
413         configFile->beginGroup(groupKey);
414         configFile->setValue(g_settingsId_versionNumber, QApplication::applicationVersion());
415         configFile->sync();
416
417         //Create the cache
418         m_configCache = new SettingsCache(configFile.take());
419 }
420
421 ////////////////////////////////////////////////////////////
422 // Destructor
423 ////////////////////////////////////////////////////////////
424
425 SettingsModel::~SettingsModel(void)
426 {
427         MUTILS_DELETE(m_configCache);
428 }
429
430 ////////////////////////////////////////////////////////////
431 // Public Functions
432 ////////////////////////////////////////////////////////////
433
434 #define CHECK_RCMODE(NAME) do\
435 { \
436         if(this->compressionRCMode##NAME() < SettingsModel::VBRMode || this->compressionRCMode##NAME() >= SettingsModel::RCMODE_COUNT) \
437         { \
438                 this->compressionRCMode##NAME(SettingsModel::VBRMode); \
439         } \
440 } \
441 while(0)
442
443 void SettingsModel::validate(void)
444 {
445         if(this->compressionEncoder() < SettingsModel::MP3Encoder || this->compressionEncoder() >= SettingsModel::ENCODER_COUNT)
446         {
447                 this->compressionEncoder(SettingsModel::MP3Encoder);
448         }
449         
450         CHECK_RCMODE(LAME);
451         CHECK_RCMODE(OggEnc);
452         CHECK_RCMODE(AacEnc);
453         CHECK_RCMODE(Aften);
454         CHECK_RCMODE(OpusEnc);
455         
456         if(EncoderRegistry::getAacEncoder() == AAC_ENCODER_NONE)
457         {
458                 if(this->compressionEncoder() == SettingsModel::AACEncoder)
459                 {
460                         qWarning("AAC encoder selected, but not available any more. Reverting to MP3!");
461                         this->compressionEncoder(SettingsModel::MP3Encoder);
462                 }
463         }
464         
465         if(this->outputDir().isEmpty() || (!dir_exists(this->outputDir())))
466         {
467                 qWarning("Output directory not set yet or does NOT exist anymore -> resetting!");
468                 const QString outputDir = find_existing_ancestor(this->outputDir());
469                 this->outputDir((!outputDir.isEmpty()) ? outputDir : defaultDirectory());
470         }
471
472         if(this->mostRecentInputPath().isEmpty() || (!dir_exists(this->mostRecentInputPath())))
473         {
474                 qWarning("Most recent input directory not set yet or does NOT exist anymore -> resetting!");
475                 const QString inputPath = find_existing_ancestor(this->mostRecentInputPath());
476                 this->mostRecentInputPath((!inputPath.isEmpty()) ? inputPath : defaultDirectory());
477         }
478
479         if(!this->currentLanguageFile().isEmpty())
480         {
481                 const QString qmPath = QFileInfo(this->currentLanguageFile()).canonicalFilePath();
482                 if(qmPath.isEmpty() || (!(QFileInfo(qmPath).exists() && QFileInfo(qmPath).isFile() && (QFileInfo(qmPath).suffix().compare("qm", Qt::CaseInsensitive) == 0))))
483                 {
484                         qWarning("Current language file missing, reverting to built-in translator!");
485                         this->currentLanguageFile(QString());
486                 }
487         }
488
489         QStringList translations;
490         if(MUtils::Translation::enumerate(translations) > 0)
491         {
492                 if(!translations.contains(this->currentLanguage(), Qt::CaseInsensitive))
493                 {
494                         qWarning("Current language \"%s\" is unknown, reverting to default language!", this->currentLanguage().toLatin1().constData());
495                         this->currentLanguage(defaultLanguage());
496                 }
497         }
498
499         if(this->hibernateComputer())
500         {
501                 if(!MUtils::OS::is_hibernation_supported())
502                 {
503                         this->hibernateComputer(false);
504                 }
505         }
506
507         if(this->overwriteMode() < SettingsModel::Overwrite_KeepBoth || this->overwriteMode() > SettingsModel::Overwrite_Replaces)
508         {
509                 this->overwriteMode(SettingsModel::Overwrite_KeepBoth);
510         }
511 }
512
513 void SettingsModel::syncNow(void)
514 {
515         m_configCache->flushValues();
516 }
517
518 ////////////////////////////////////////////////////////////
519 // Private Functions
520 ////////////////////////////////////////////////////////////
521
522 QString SettingsModel::defaultLanguage(void) const
523 {
524         QMutexLocker lock(&m_defaultLangLock);
525
526         //Default already initialized?
527         if(!m_defaultLanguage.isNull())
528         {
529                 return *m_defaultLanguage;
530         }
531
532         //Detect system langauge
533         QLocale systemLanguage= QLocale::system();
534         qDebug("[Locale]");
535         qDebug("Language: %s (%d)", MUTILS_UTF8(QLocale::languageToString(systemLanguage.language())), systemLanguage.language());
536         qDebug("Country is: %s (%d)", MUTILS_UTF8(QLocale::countryToString(systemLanguage.country())), systemLanguage.country());
537         qDebug("Script is: %s (%d)\n", MUTILS_UTF8(QLocale::scriptToString(systemLanguage.script())), systemLanguage.script());
538
539         //Check if we can use the default translation
540         if(systemLanguage.language() == QLocale::English /*|| systemLanguage.language() == QLocale::C*/)
541         {
542                 m_defaultLanguage.reset(new QString(MUtils::Translation::DEFAULT_LANGID));
543                 return MUtils::Translation::DEFAULT_LANGID;
544         }
545
546         QStringList languages;
547         if(MUtils::Translation::enumerate(languages) > 0)
548         {
549                 //Try to find a suitable translation for the user's system language *and* country
550                 for(QStringList::ConstIterator iter = languages.constBegin(); iter != languages.constEnd(); iter++)
551                 {
552                         if(MUtils::Translation::get_sysid(*iter) == static_cast<quint32>(systemLanguage.language()))
553                         {
554                                 if(MUtils::Translation::get_country(*iter) == static_cast<quint32>(systemLanguage.country()))
555                                 {
556                                         m_defaultLanguage.reset(new QString(*iter));
557                                         return (*iter);
558                                 }
559                         }
560                 }
561
562                 //Try to find a suitable translation for the user's system language
563                 for(QStringList::ConstIterator iter = languages.constBegin(); iter != languages.constEnd(); iter++)
564                 {
565                         if(MUtils::Translation::get_sysid(*iter) == static_cast<quint32>(systemLanguage.language()))
566                         {
567                                 m_defaultLanguage.reset(new QString(*iter));
568                                 return (*iter);
569                         }
570                 }
571         }
572
573         //Fall back to the default translation
574         m_defaultLanguage.reset(new QString(MUtils::Translation::DEFAULT_LANGID));
575         return MUtils::Translation::DEFAULT_LANGID;
576 }
577
578 QString SettingsModel::defaultDirectory(void) const
579 {
580         QString defaultLocation = initDirectory(QDesktopServices::storageLocation(QDesktopServices::MusicLocation));
581
582         if(defaultLocation.isEmpty())
583         {
584                 defaultLocation = initDirectory(QDesktopServices::storageLocation(QDesktopServices::HomeLocation));
585
586                 if(defaultLocation.isEmpty())
587                 {
588                         defaultLocation = initDirectory(QDir::currentPath());
589                 }
590         }
591
592         return defaultLocation;
593 }
594
595 QString SettingsModel::initDirectory(const QString &path) const
596 {
597         if(path.isEmpty())
598         {
599                 return QString();
600         }
601
602         if(!QDir(path).exists())
603         {
604                 for(int i = 0; i < 32; i++)
605                 {
606                         if(QDir(path).mkpath(".")) break;
607                         MUtils::OS::sleep_ms(1);
608                 }
609         }
610
611         if(!QDir(path).exists())
612         {
613                 return QString();
614         }
615         
616         return QDir(path).canonicalPath();
617 }
618
619 ////////////////////////////////////////////////////////////
620 // Getter and Setter
621 ////////////////////////////////////////////////////////////
622
623 LAMEXP_MAKE_OPTION_I(aacEncProfile, 0)
624 LAMEXP_MAKE_OPTION_I(aftenAudioCodingMode, 0)
625 LAMEXP_MAKE_OPTION_I(aftenDynamicRangeCompression, 5)
626 LAMEXP_MAKE_OPTION_I(aftenExponentSearchSize, 8)
627 LAMEXP_MAKE_OPTION_B(aftenFastBitAllocation, false)
628 LAMEXP_MAKE_OPTION_B(antivirNotificationsEnabled, true)
629 LAMEXP_MAKE_OPTION_B(autoUpdateCheckBeta, false)
630 LAMEXP_MAKE_OPTION_B(autoUpdateEnabled, (!lamexp_version_portable()));
631 LAMEXP_MAKE_OPTION_S(autoUpdateLastCheck, "Never")
632 LAMEXP_MAKE_OPTION_B(bitrateManagementEnabled, false)
633 LAMEXP_MAKE_OPTION_I(bitrateManagementMaxRate, 500)
634 LAMEXP_MAKE_OPTION_I(bitrateManagementMinRate, 32)
635 LAMEXP_MAKE_OPTION_I(compressionAbrBitrateAacEnc, 19)
636 LAMEXP_MAKE_OPTION_I(compressionAbrBitrateAften, 17)
637 LAMEXP_MAKE_OPTION_I(compressionAbrBitrateDcaEnc, 13)
638 LAMEXP_MAKE_OPTION_I(compressionAbrBitrateFLAC, 5)
639 LAMEXP_MAKE_OPTION_I(compressionAbrBitrateLAME, 10)
640 LAMEXP_MAKE_OPTION_I(compressionAbrBitrateMacEnc, 2)
641 LAMEXP_MAKE_OPTION_I(compressionAbrBitrateOggEnc, 16)
642 LAMEXP_MAKE_OPTION_I(compressionAbrBitrateOpusEnc, 11)
643 LAMEXP_MAKE_OPTION_I(compressionAbrBitrateWave, 0)
644 LAMEXP_MAKE_OPTION_I(compressionCbrBitrateAacEnc, 19)
645 LAMEXP_MAKE_OPTION_I(compressionCbrBitrateAften, 17)
646 LAMEXP_MAKE_OPTION_I(compressionCbrBitrateDcaEnc, 13)
647 LAMEXP_MAKE_OPTION_I(compressionCbrBitrateFLAC, 5)
648 LAMEXP_MAKE_OPTION_I(compressionCbrBitrateLAME, 10)
649 LAMEXP_MAKE_OPTION_I(compressionCbrBitrateMacEnc, 2)
650 LAMEXP_MAKE_OPTION_I(compressionCbrBitrateOggEnc, 16)
651 LAMEXP_MAKE_OPTION_I(compressionCbrBitrateOpusEnc, 11)
652 LAMEXP_MAKE_OPTION_I(compressionCbrBitrateWave, 0)
653 LAMEXP_MAKE_OPTION_I(compressionEncoder, 0)
654 LAMEXP_MAKE_OPTION_I(compressionRCModeAacEnc, 0)
655 LAMEXP_MAKE_OPTION_I(compressionRCModeAften, 0)
656 LAMEXP_MAKE_OPTION_I(compressionRCModeDcaEnc, 2)
657 LAMEXP_MAKE_OPTION_I(compressionRCModeFLAC, 0)
658 LAMEXP_MAKE_OPTION_I(compressionRCModeLAME, 0)
659 LAMEXP_MAKE_OPTION_I(compressionRCModeMacEnc, 0)
660 LAMEXP_MAKE_OPTION_I(compressionRCModeOggEnc, 0)
661 LAMEXP_MAKE_OPTION_I(compressionRCModeOpusEnc, 0)
662 LAMEXP_MAKE_OPTION_I(compressionRCModeWave, 2)
663 LAMEXP_MAKE_OPTION_I(compressionVbrQualityAacEnc, 10)
664 LAMEXP_MAKE_OPTION_I(compressionVbrQualityAften, 15)
665 LAMEXP_MAKE_OPTION_I(compressionVbrQualityDcaEnc, 13)
666 LAMEXP_MAKE_OPTION_I(compressionVbrQualityFLAC, 5)
667 LAMEXP_MAKE_OPTION_I(compressionVbrQualityLAME, 7)
668 LAMEXP_MAKE_OPTION_I(compressionVbrQualityMacEnc, 2)
669 LAMEXP_MAKE_OPTION_I(compressionVbrQualityOggEnc, 7)
670 LAMEXP_MAKE_OPTION_I(compressionVbrQualityOpusEnc, 11)
671 LAMEXP_MAKE_OPTION_I(compressionVbrQualityWave, 0)
672 LAMEXP_MAKE_OPTION_B(createPlaylist, true)
673 LAMEXP_MAKE_OPTION_S(currentLanguage, defaultLanguage())
674 LAMEXP_MAKE_OPTION_S(currentLanguageFile, QString())
675 LAMEXP_MAKE_OPTION_S(customParametersAacEnc, QString())
676 LAMEXP_MAKE_OPTION_S(customParametersAften, QString())
677 LAMEXP_MAKE_OPTION_S(customParametersDcaEnc, QString())
678 LAMEXP_MAKE_OPTION_S(customParametersFLAC, QString())
679 LAMEXP_MAKE_OPTION_S(customParametersLAME, QString())
680 LAMEXP_MAKE_OPTION_S(customParametersMacEnc, QString())
681 LAMEXP_MAKE_OPTION_S(customParametersOggEnc, QString())
682 LAMEXP_MAKE_OPTION_S(customParametersOpusEnc, QString())
683 LAMEXP_MAKE_OPTION_S(customParametersWave, QString())
684 LAMEXP_MAKE_OPTION_S(customTempPath, QDesktopServices::storageLocation(QDesktopServices::TempLocation))
685 LAMEXP_MAKE_OPTION_B(customTempPathEnabled, false)
686 LAMEXP_MAKE_OPTION_B(disableTrayIcon, true)
687 LAMEXP_MAKE_OPTION_B(dropBoxWidgetEnabled, true)
688 LAMEXP_MAKE_OPTION_I(dropBoxWidgetPositionX, -1)
689 LAMEXP_MAKE_OPTION_I(dropBoxWidgetPositionY, -1)
690 LAMEXP_MAKE_OPTION_S(favoriteOutputFolders, QString())
691 LAMEXP_MAKE_OPTION_B(forceStereoDownmix, false)
692 LAMEXP_MAKE_OPTION_B(hibernateComputer, false)
693 LAMEXP_MAKE_OPTION_I(interfaceStyle, 0)
694 LAMEXP_MAKE_OPTION_B(keepOriginalDataTime, false)
695 LAMEXP_MAKE_OPTION_I(lameAlgoQuality, 2)
696 LAMEXP_MAKE_OPTION_I(lameChannelMode, 0)
697 LAMEXP_MAKE_OPTION_I(licenseAccepted, 0)
698 LAMEXP_MAKE_OPTION_U(maximumInstances, 0)
699 LAMEXP_MAKE_OPTION_U(metaInfoPosition, UINT_MAX)
700 LAMEXP_MAKE_OPTION_S(mostRecentInputPath, defaultDirectory())
701 LAMEXP_MAKE_OPTION_B(neroAACEnable2Pass, true)
702 LAMEXP_MAKE_OPTION_B(neroAacNotificationsEnabled, true)
703 LAMEXP_MAKE_OPTION_B(normalizationFilterEnabled, false)
704 LAMEXP_MAKE_OPTION_B(normalizationFilterDynamic, false)
705 LAMEXP_MAKE_OPTION_B(normalizationFilterCoupled, true)
706 LAMEXP_MAKE_OPTION_I(normalizationFilterMaxVolume, -50)
707 LAMEXP_MAKE_OPTION_I(normalizationFilterSize, 31)
708 LAMEXP_MAKE_OPTION_I(opusComplexity, 10)
709 LAMEXP_MAKE_OPTION_B(opusDisableResample, false)
710 LAMEXP_MAKE_OPTION_I(opusFramesize, 3)
711 LAMEXP_MAKE_OPTION_I(opusOptimizeFor, 0)
712 LAMEXP_MAKE_OPTION_S(outputDir, defaultDirectory())
713 LAMEXP_MAKE_OPTION_B(outputToSourceDir, false)
714 LAMEXP_MAKE_OPTION_I(overwriteMode, Overwrite_KeepBoth)
715 LAMEXP_MAKE_OPTION_B(prependRelativeSourcePath, false)
716 LAMEXP_MAKE_OPTION_B(renameFiles_regExpEnabled, false)
717 LAMEXP_MAKE_OPTION_S(renameFiles_regExpSearch, QString())
718 LAMEXP_MAKE_OPTION_S(renameFiles_regExpReplace, QString())
719 LAMEXP_MAKE_OPTION_B(renameFiles_renameEnabled, false)
720 LAMEXP_MAKE_OPTION_S(renameFiles_renamePattern, "[<TrackNo>] <Artist> - <Title>")
721 LAMEXP_MAKE_OPTION_S(renameFiles_fileExtension, QString())
722 LAMEXP_MAKE_OPTION_I(samplingRate, 0)
723 LAMEXP_MAKE_OPTION_B(shellIntegrationEnabled, !lamexp_version_portable())
724 LAMEXP_MAKE_OPTION_B(slowStartup, false)
725 LAMEXP_MAKE_OPTION_B(soundsEnabled, true)
726 LAMEXP_MAKE_OPTION_I(toneAdjustBass, 0)
727 LAMEXP_MAKE_OPTION_I(toneAdjustTreble, 0)
728 LAMEXP_MAKE_OPTION_B(writeMetaTags, true)