OSDN Git Service

716ee5c4410cc27bc652b052422d455526332056
[lamexp/LameXP.git] / src / Model_Settings.cpp
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.
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 *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 int SettingsModel::OPT(void) const { return m_configCache->loadValue(g_settingsId_##OPT, (DEF)).toInt(); } \
151 void SettingsModel::OPT(int value) { m_configCache->storeValue(g_settingsId_##OPT, value); } \
152 int 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 unsigned int SettingsModel::OPT(void) const { return m_configCache->loadValue(g_settingsId_##OPT, (DEF)).toUInt(); } \
166 void SettingsModel::OPT(unsigned int value) { m_configCache->storeValue(g_settingsId_##OPT, value); } \
167 unsigned int 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 #define DIR_EXISTS(PATH) (QFileInfo(PATH).exists() && QFileInfo(PATH).isDir())
180
181 ////////////////////////////////////////////////////////////
182 // Constants
183 ////////////////////////////////////////////////////////////
184
185 //Setting ID's
186 LAMEXP_MAKE_ID(aacEncProfile,                "AdvancedOptions/AACEnc/ForceProfile");
187 LAMEXP_MAKE_ID(aftenAudioCodingMode,         "AdvancedOptions/Aften/AudioCodingMode");
188 LAMEXP_MAKE_ID(aftenDynamicRangeCompression, "AdvancedOptions/Aften/DynamicRangeCompression");
189 LAMEXP_MAKE_ID(aftenExponentSearchSize,      "AdvancedOptions/Aften/ExponentSearchSize");
190 LAMEXP_MAKE_ID(aftenFastBitAllocation,       "AdvancedOptions/Aften/FastBitAllocation");
191 LAMEXP_MAKE_ID(antivirNotificationsEnabled,  "Flags/EnableAntivirusNotifications");
192 LAMEXP_MAKE_ID(autoUpdateCheckBeta,          "AutoUpdate/CheckForBetaVersions");
193 LAMEXP_MAKE_ID(autoUpdateEnabled,            "AutoUpdate/Enabled");
194 LAMEXP_MAKE_ID(autoUpdateLastCheck,          "AutoUpdate/LastCheck");
195 LAMEXP_MAKE_ID(bitrateManagementEnabled,     "AdvancedOptions/BitrateManagement/Enabled");
196 LAMEXP_MAKE_ID(bitrateManagementMaxRate,     "AdvancedOptions/BitrateManagement/MaxRate");
197 LAMEXP_MAKE_ID(bitrateManagementMinRate,     "AdvancedOptions/BitrateManagement/MinRate");
198 LAMEXP_MAKE_ID(compressionAbrBitrateAacEnc,  "Compression/AbrTaretBitrate/AacEnc");
199 LAMEXP_MAKE_ID(compressionAbrBitrateAften,   "Compression/AbrTaretBitrate/Aften");
200 LAMEXP_MAKE_ID(compressionAbrBitrateDcaEnc,  "Compression/AbrTaretBitrate/DcaEnc");
201 LAMEXP_MAKE_ID(compressionAbrBitrateFLAC,    "Compression/AbrTaretBitrate/FLAC");
202 LAMEXP_MAKE_ID(compressionAbrBitrateLAME,    "Compression/AbrTaretBitrate/LAME");
203 LAMEXP_MAKE_ID(compressionAbrBitrateMacEnc,  "Compression/AbrTaretBitrate/MacEnc");
204 LAMEXP_MAKE_ID(compressionAbrBitrateOggEnc,  "Compression/AbrTaretBitrate/OggEnc");
205 LAMEXP_MAKE_ID(compressionAbrBitrateOpusEnc, "Compression/AbrTaretBitrate/OpusEnc");
206 LAMEXP_MAKE_ID(compressionAbrBitrateWave,    "Compression/AbrTaretBitrate/Wave");
207 LAMEXP_MAKE_ID(compressionCbrBitrateAacEnc,  "Compression/CbrTaretBitrate/AacEnc");
208 LAMEXP_MAKE_ID(compressionCbrBitrateAften,   "Compression/CbrTaretBitrate/Aften");
209 LAMEXP_MAKE_ID(compressionCbrBitrateDcaEnc,  "Compression/CbrTaretBitrate/DcaEnc");
210 LAMEXP_MAKE_ID(compressionCbrBitrateFLAC,    "Compression/CbrTaretBitrate/FLAC");
211 LAMEXP_MAKE_ID(compressionCbrBitrateLAME,    "Compression/CbrTaretBitrate/LAME");
212 LAMEXP_MAKE_ID(compressionCbrBitrateMacEnc,  "Compression/CbrTaretBitrate/MacEnc");
213 LAMEXP_MAKE_ID(compressionCbrBitrateOggEnc,  "Compression/CbrTaretBitrate/OggEnc");
214 LAMEXP_MAKE_ID(compressionCbrBitrateOpusEnc, "Compression/CbrTaretBitrate/OpusEnc");
215 LAMEXP_MAKE_ID(compressionCbrBitrateWave,    "Compression/CbrTaretBitrate/Wave");
216 LAMEXP_MAKE_ID(compressionEncoder,           "Compression/Encoder");
217 LAMEXP_MAKE_ID(compressionRCModeAacEnc,      "Compression/RCMode/AacEnc");
218 LAMEXP_MAKE_ID(compressionRCModeAften,       "Compression/RCMode/Aften");
219 LAMEXP_MAKE_ID(compressionRCModeDcaEnc,      "Compression/RCMode/DcaEnc");
220 LAMEXP_MAKE_ID(compressionRCModeFLAC,        "Compression/RCMode/FLAC");
221 LAMEXP_MAKE_ID(compressionRCModeLAME,        "Compression/RCMode/LAME");
222 LAMEXP_MAKE_ID(compressionRCModeMacEnc,      "Compression/RCMode/MacEnc");
223 LAMEXP_MAKE_ID(compressionRCModeOggEnc,      "Compression/RCMode/OggEnc");
224 LAMEXP_MAKE_ID(compressionRCModeOpusEnc,     "Compression/RCMode/OpusEnc");
225 LAMEXP_MAKE_ID(compressionRCModeWave,        "Compression/RCMode/Wave");
226 LAMEXP_MAKE_ID(compressionVbrQualityAacEnc,  "Compression/VbrQualityLevel/AacEnc");
227 LAMEXP_MAKE_ID(compressionVbrQualityAften,   "Compression/VbrQualityLevel/Aften");
228 LAMEXP_MAKE_ID(compressionVbrQualityDcaEnc,  "Compression/VbrQualityLevel/DcaEnc");
229 LAMEXP_MAKE_ID(compressionVbrQualityFLAC,    "Compression/VbrQualityLevel/FLAC");
230 LAMEXP_MAKE_ID(compressionVbrQualityLAME,    "Compression/VbrQualityLevel/LAME");
231 LAMEXP_MAKE_ID(compressionVbrQualityMacEnc,  "Compression/VbrQualityLevel/MacEnc");
232 LAMEXP_MAKE_ID(compressionVbrQualityOggEnc,  "Compression/VbrQualityLevel/OggEnc");
233 LAMEXP_MAKE_ID(compressionVbrQualityOpusEnc, "Compression/VbrQualityLevel/OpusEnc");
234 LAMEXP_MAKE_ID(compressionVbrQualityWave,    "Compression/VbrQualityLevel/Wave");
235 LAMEXP_MAKE_ID(createPlaylist,               "Flags/AutoCreatePlaylist");
236 LAMEXP_MAKE_ID(currentLanguage,              "Localization/Language");
237 LAMEXP_MAKE_ID(currentLanguageFile,          "Localization/UseQMFile");
238 LAMEXP_MAKE_ID(customParametersAacEnc,       "AdvancedOptions/CustomParameters/AacEnc");
239 LAMEXP_MAKE_ID(customParametersAften,        "AdvancedOptions/CustomParameters/Aften");
240 LAMEXP_MAKE_ID(customParametersDcaEnc,       "AdvancedOptions/CustomParameters/DcaEnc");
241 LAMEXP_MAKE_ID(customParametersFLAC,         "AdvancedOptions/CustomParameters/FLAC");
242 LAMEXP_MAKE_ID(customParametersLAME,         "AdvancedOptions/CustomParameters/LAME");
243 LAMEXP_MAKE_ID(customParametersMacEnc,       "AdvancedOptions/CustomParameters/MacEnc");
244 LAMEXP_MAKE_ID(customParametersOggEnc,       "AdvancedOptions/CustomParameters/OggEnc");
245 LAMEXP_MAKE_ID(customParametersOpusEnc,      "AdvancedOptions/CustomParameters/OpusEnc");
246 LAMEXP_MAKE_ID(customParametersWave,         "AdvancedOptions/CustomParameters/Wave");
247 LAMEXP_MAKE_ID(customTempPath,               "AdvancedOptions/TempDirectory/CustomPath");
248 LAMEXP_MAKE_ID(customTempPathEnabled,        "AdvancedOptions/TempDirectory/UseCustomPath");
249 LAMEXP_MAKE_ID(dropBoxWidgetEnabled,         "DropBoxWidget/Enabled");
250 LAMEXP_MAKE_ID(dropBoxWidgetPositionX,       "DropBoxWidget/Position/X");
251 LAMEXP_MAKE_ID(dropBoxWidgetPositionY,       "DropBoxWidget/Position/Y");
252 LAMEXP_MAKE_ID(favoriteOutputFolders,        "OutputDirectory/Favorites");
253 LAMEXP_MAKE_ID(forceStereoDownmix,           "AdvancedOptions/StereoDownmix/Force");
254 LAMEXP_MAKE_ID(hibernateComputer,            "AdvancedOptions/HibernateComputerOnShutdown");
255 LAMEXP_MAKE_ID(interfaceStyle,               "InterfaceStyle");
256 LAMEXP_MAKE_ID(lameAlgoQuality,              "AdvancedOptions/LAME/AlgorithmQuality");
257 LAMEXP_MAKE_ID(lameChannelMode,              "AdvancedOptions/LAME/ChannelMode");
258 LAMEXP_MAKE_ID(licenseAccepted,              "LicenseAccepted");
259 LAMEXP_MAKE_ID(maximumInstances,             "AdvancedOptions/Threading/MaximumInstances");
260 LAMEXP_MAKE_ID(metaInfoPosition,             "MetaInformation/PlaylistPosition");
261 LAMEXP_MAKE_ID(mostRecentInputPath,          "InputDirectory/MostRecentPath");
262 LAMEXP_MAKE_ID(neroAACEnable2Pass,           "AdvancedOptions/AACEnc/Enable2Pass");
263 LAMEXP_MAKE_ID(neroAacNotificationsEnabled,  "Flags/EnableNeroAacNotifications");
264 LAMEXP_MAKE_ID(normalizationFilterEnabled,   "AdvancedOptions/VolumeNormalization/Enabled");
265 LAMEXP_MAKE_ID(normalizationFilterEQMode,    "AdvancedOptions/VolumeNormalization/EqualizationMode");
266 LAMEXP_MAKE_ID(normalizationFilterMaxVolume, "AdvancedOptions/VolumeNormalization/MaxVolume");
267 LAMEXP_MAKE_ID(opusComplexity,               "AdvancedOptions/Opus/EncodingComplexity");
268 LAMEXP_MAKE_ID(opusDisableResample,          "AdvancedOptions/Opus/DisableResample");
269 LAMEXP_MAKE_ID(opusFramesize,                "AdvancedOptions/Opus/FrameSize");
270 LAMEXP_MAKE_ID(opusOptimizeFor,              "AdvancedOptions/Opus/OptimizeForSignalType");
271 LAMEXP_MAKE_ID(outputDir,                    "OutputDirectory/SelectedPath");
272 LAMEXP_MAKE_ID(outputToSourceDir,            "OutputDirectory/OutputToSourceFolder");
273 LAMEXP_MAKE_ID(overwriteMode,                "AdvancedOptions/OverwriteMode");
274 LAMEXP_MAKE_ID(prependRelativeSourcePath,    "OutputDirectory/PrependRelativeSourcePath");
275 LAMEXP_MAKE_ID(renameOutputFilesEnabled,     "AdvancedOptions/RenameOutputFiles/Enabled");
276 LAMEXP_MAKE_ID(renameOutputFilesPattern,     "AdvancedOptions/RenameOutputFiles/Pattern");
277 LAMEXP_MAKE_ID(samplingRate,                 "AdvancedOptions/Common/Resampling");
278 LAMEXP_MAKE_ID(shellIntegrationEnabled,      "Flags/EnableShellIntegration");
279 LAMEXP_MAKE_ID(slowStartup,                  "Flags/SlowStartupDetected");
280 LAMEXP_MAKE_ID(soundsEnabled,                "Flags/EnableSounds");
281 LAMEXP_MAKE_ID(toneAdjustBass,               "AdvancedOptions/ToneAdjustment/Bass");
282 LAMEXP_MAKE_ID(toneAdjustTreble,             "AdvancedOptions/ToneAdjustment/Treble");
283 LAMEXP_MAKE_ID(versionNumber,                "VersionNumber");
284 LAMEXP_MAKE_ID(writeMetaTags,                "Flags/WriteMetaTags");
285
286 //LUT
287 const int SettingsModel::samplingRates[8] = {0, 16000, 22050, 24000, 32000, 44100, 48000, -1};
288
289 ////////////////////////////////////////////////////////////
290 // Constructor
291 ////////////////////////////////////////////////////////////
292
293 SettingsModel::SettingsModel(void)
294 :
295         m_configCache(NULL)
296 {
297         QString configPath = "LameXP.ini";
298         
299         if(!lamexp_version_portable())
300         {
301                 QString dataPath = initDirectory(QDesktopServices::storageLocation(QDesktopServices::DataLocation));
302                 if(!dataPath.isEmpty())
303                 {
304                         configPath = QString("%1/config.ini").arg(QDir(dataPath).canonicalPath());
305                 }
306                 else
307                 {
308                         qWarning("SettingsModel: DataLocation could not be initialized!");
309                         dataPath = initDirectory(QDesktopServices::storageLocation(QDesktopServices::HomeLocation));
310                         if(!dataPath.isEmpty())
311                         {
312                                 configPath = QString("%1/LameXP.ini").arg(QDir(dataPath).canonicalPath());
313                         }
314                 }
315         }
316         else
317         {
318                 qDebug("LameXP is running in \"portable\" mode -> config in application dir!\n");
319                 QString appPath = QFileInfo(QApplication::applicationFilePath()).canonicalFilePath();
320                 if(appPath.isEmpty())
321                 {
322                         appPath = QFileInfo(QApplication::applicationFilePath()).absoluteFilePath();
323                 }
324                 if(QFileInfo(appPath).exists() && QFileInfo(appPath).isFile())
325                 {
326                         configPath = QString("%1/%2.ini").arg(QFileInfo(appPath).absolutePath(), QFileInfo(appPath).completeBaseName());
327                 }
328         }
329
330         //Create settings
331         QSettings *configFile = new QSettings(configPath, QSettings::IniFormat);
332         const QString groupKey = QString().sprintf("LameXP_%u%02u%05u", lamexp_version_major(), lamexp_version_minor(), lamexp_version_confg());
333         QStringList childGroups =configFile->childGroups();
334
335         //Clean-up settings
336         while(!childGroups.isEmpty())
337         {
338                 QString current = childGroups.takeFirst();
339                 QRegExp filter("^LameXP_(\\d+)(\\d\\d)(\\d\\d\\d\\d\\d)$");
340                 if(filter.indexIn(current) >= 0)
341                 {
342                         bool ok = false;
343                         unsigned int temp = filter.cap(3).toUInt(&ok) + 10;
344                         if(ok && (temp >= lamexp_version_confg()))
345                         {
346                                 continue;
347                         }
348                 }
349                 qWarning("Deleting obsolete group from config: %s", MUTILS_UTF8(current));
350                 REMOVE_GROUP(configFile, current);
351         }
352
353         //Setup settings
354         configFile->beginGroup(groupKey);
355         configFile->setValue(g_settingsId_versionNumber, QApplication::applicationVersion());
356         configFile->sync();
357
358         //Create the cache
359         m_configCache = new SettingsCache(configFile);
360 }
361
362 ////////////////////////////////////////////////////////////
363 // Destructor
364 ////////////////////////////////////////////////////////////
365
366 SettingsModel::~SettingsModel(void)
367 {
368         MUTILS_DELETE(m_configCache);
369 }
370
371 ////////////////////////////////////////////////////////////
372 // Public Functions
373 ////////////////////////////////////////////////////////////
374
375 #define CHECK_RCMODE(NAME) do\
376 { \
377         if(this->compressionRCMode##NAME() < SettingsModel::VBRMode || this->compressionRCMode##NAME() >= SettingsModel::RCMODE_COUNT) \
378         { \
379                 this->compressionRCMode##NAME(SettingsModel::VBRMode); \
380         } \
381 } \
382 while(0)
383
384 void SettingsModel::validate(void)
385 {
386         if(this->compressionEncoder() < SettingsModel::MP3Encoder || this->compressionEncoder() >= SettingsModel::ENCODER_COUNT)
387         {
388                 this->compressionEncoder(SettingsModel::MP3Encoder);
389         }
390         
391         CHECK_RCMODE(LAME);
392         CHECK_RCMODE(OggEnc);
393         CHECK_RCMODE(AacEnc);
394         CHECK_RCMODE(Aften);
395         CHECK_RCMODE(OpusEnc);
396         
397         if(EncoderRegistry::getAacEncoder() == AAC_ENCODER_NONE)
398         {
399                 if(this->compressionEncoder() == SettingsModel::AACEncoder)
400                 {
401                         qWarning("AAC encoder selected, but not available any more. Reverting to MP3!");
402                         this->compressionEncoder(SettingsModel::MP3Encoder);
403                 }
404         }
405         
406         if(this->outputDir().isEmpty() || (!DIR_EXISTS(this->outputDir())))
407         {
408                 qWarning("Output directory not set yet or does NOT exist anymore -> Resetting");
409                 this->outputDir(defaultDirectory());
410         }
411
412         if(this->mostRecentInputPath().isEmpty() || (!DIR_EXISTS(this->mostRecentInputPath())))
413         {
414                 qWarning("Most recent input directory not set yet or does NOT exist anymore -> Resetting");
415                 this->mostRecentInputPath(defaultDirectory());
416         }
417
418         if(!this->currentLanguageFile().isEmpty())
419         {
420                 const QString qmPath = QFileInfo(this->currentLanguageFile()).canonicalFilePath();
421                 if(qmPath.isEmpty() || (!(QFileInfo(qmPath).exists() && QFileInfo(qmPath).isFile() && (QFileInfo(qmPath).suffix().compare("qm", Qt::CaseInsensitive) == 0))))
422                 {
423                         qWarning("Current language file missing, reverting to built-in translator!");
424                         this->currentLanguageFile(QString());
425                 }
426         }
427
428         QStringList translations;
429         if(MUtils::Translation::enumerate(translations) > 0)
430         {
431                 if(!translations.contains(this->currentLanguage(), Qt::CaseInsensitive))
432                 {
433                         qWarning("Current language \"%s\" is unknown, reverting to default language!", this->currentLanguage().toLatin1().constData());
434                         this->currentLanguage(defaultLanguage());
435                 }
436         }
437
438         if(this->hibernateComputer())
439         {
440                 if(!MUtils::OS::is_hibernation_supported())
441                 {
442                         this->hibernateComputer(false);
443                 }
444         }
445
446         if(this->overwriteMode() < SettingsModel::Overwrite_KeepBoth || this->overwriteMode() > SettingsModel::Overwrite_Replaces)
447         {
448                 this->overwriteMode(SettingsModel::Overwrite_KeepBoth);
449         }
450 }
451
452 void SettingsModel::syncNow(void)
453 {
454         m_configCache->flushValues();
455 }
456
457 ////////////////////////////////////////////////////////////
458 // Private Functions
459 ////////////////////////////////////////////////////////////
460
461 QString SettingsModel::defaultLanguage(void) const
462 {
463         QMutexLocker lock(&m_defaultLangLock);
464
465         //Default already initialized?
466         if(!m_defaultLanguage.isNull())
467         {
468                 return *m_defaultLanguage;
469         }
470
471         //Detect system langauge
472         QLocale systemLanguage= QLocale::system();
473         qDebug("[Locale]");
474         qDebug("Language: %s (%d)", MUTILS_UTF8(QLocale::languageToString(systemLanguage.language())), systemLanguage.language());
475         qDebug("Country is: %s (%d)", MUTILS_UTF8(QLocale::countryToString(systemLanguage.country())), systemLanguage.country());
476         qDebug("Script is: %s (%d)\n", MUTILS_UTF8(QLocale::scriptToString(systemLanguage.script())), systemLanguage.script());
477
478         //Check if we can use the default translation
479         if(systemLanguage.language() == QLocale::English /*|| systemLanguage.language() == QLocale::C*/)
480         {
481                 m_defaultLanguage.reset(new QString(MUtils::Translation::DEFAULT_LANGID));
482                 return MUtils::Translation::DEFAULT_LANGID;
483         }
484
485         QStringList languages;
486         if(MUtils::Translation::enumerate(languages) > 0)
487         {
488                 //Try to find a suitable translation for the user's system language *and* country
489                 for(QStringList::ConstIterator iter = languages.constBegin(); iter != languages.constEnd(); iter++)
490                 {
491                         if(MUtils::Translation::get_sysid(*iter) == systemLanguage.language())
492                         {
493                                 if(MUtils::Translation::get_country(*iter) == systemLanguage.country())
494                                 {
495                                         m_defaultLanguage.reset(new QString(*iter));
496                                         return (*iter);
497                                 }
498                         }
499                 }
500
501                 //Try to find a suitable translation for the user's system language
502                 for(QStringList::ConstIterator iter = languages.constBegin(); iter != languages.constEnd(); iter++)
503                 {
504                         if(MUtils::Translation::get_sysid(*iter) == systemLanguage.language())
505                         {
506                                 m_defaultLanguage.reset(new QString(*iter));
507                                 return (*iter);
508                         }
509                 }
510         }
511
512         //Fall back to the default translation
513         m_defaultLanguage.reset(new QString(MUtils::Translation::DEFAULT_LANGID));
514         return MUtils::Translation::DEFAULT_LANGID;
515 }
516
517 QString SettingsModel::defaultDirectory(void) const
518 {
519         QString defaultLocation = initDirectory(QDesktopServices::storageLocation(QDesktopServices::MusicLocation));
520
521         if(defaultLocation.isEmpty())
522         {
523                 defaultLocation = initDirectory(QDesktopServices::storageLocation(QDesktopServices::HomeLocation));
524
525                 if(defaultLocation.isEmpty())
526                 {
527                         defaultLocation = initDirectory(QDir::currentPath());
528                 }
529         }
530
531         return defaultLocation;
532 }
533
534 QString SettingsModel::initDirectory(const QString &path) const
535 {
536         if(path.isEmpty())
537         {
538                 return QString();
539         }
540
541         if(!QDir(path).exists())
542         {
543                 for(int i = 0; i < 32; i++)
544                 {
545                         if(QDir(path).mkpath(".")) break;
546                         MUtils::OS::sleep_ms(1);
547                 }
548         }
549
550         if(!QDir(path).exists())
551         {
552                 return QString();
553         }
554         
555         return QDir(path).canonicalPath();
556 }
557
558 ////////////////////////////////////////////////////////////
559 // Getter and Setter
560 ////////////////////////////////////////////////////////////
561
562 LAMEXP_MAKE_OPTION_I(aacEncProfile, 0)
563 LAMEXP_MAKE_OPTION_I(aftenAudioCodingMode, 0)
564 LAMEXP_MAKE_OPTION_I(aftenDynamicRangeCompression, 5)
565 LAMEXP_MAKE_OPTION_I(aftenExponentSearchSize, 8)
566 LAMEXP_MAKE_OPTION_B(aftenFastBitAllocation, false)
567 LAMEXP_MAKE_OPTION_B(antivirNotificationsEnabled, true)
568 LAMEXP_MAKE_OPTION_B(autoUpdateCheckBeta, false)
569 LAMEXP_MAKE_OPTION_B(autoUpdateEnabled, (!lamexp_version_portable()));
570 LAMEXP_MAKE_OPTION_S(autoUpdateLastCheck, "Never")
571 LAMEXP_MAKE_OPTION_B(bitrateManagementEnabled, false)
572 LAMEXP_MAKE_OPTION_I(bitrateManagementMaxRate, 500)
573 LAMEXP_MAKE_OPTION_I(bitrateManagementMinRate, 32)
574 LAMEXP_MAKE_OPTION_I(compressionAbrBitrateAacEnc, 19)
575 LAMEXP_MAKE_OPTION_I(compressionAbrBitrateAften, 17)
576 LAMEXP_MAKE_OPTION_I(compressionAbrBitrateDcaEnc, 13)
577 LAMEXP_MAKE_OPTION_I(compressionAbrBitrateFLAC, 5)
578 LAMEXP_MAKE_OPTION_I(compressionAbrBitrateLAME, 10)
579 LAMEXP_MAKE_OPTION_I(compressionAbrBitrateMacEnc, 2)
580 LAMEXP_MAKE_OPTION_I(compressionAbrBitrateOggEnc, 16)
581 LAMEXP_MAKE_OPTION_I(compressionAbrBitrateOpusEnc, 11)
582 LAMEXP_MAKE_OPTION_I(compressionAbrBitrateWave, 0)
583 LAMEXP_MAKE_OPTION_I(compressionCbrBitrateAacEnc, 19)
584 LAMEXP_MAKE_OPTION_I(compressionCbrBitrateAften, 17)
585 LAMEXP_MAKE_OPTION_I(compressionCbrBitrateDcaEnc, 13)
586 LAMEXP_MAKE_OPTION_I(compressionCbrBitrateFLAC, 5)
587 LAMEXP_MAKE_OPTION_I(compressionCbrBitrateLAME, 10)
588 LAMEXP_MAKE_OPTION_I(compressionCbrBitrateMacEnc, 2)
589 LAMEXP_MAKE_OPTION_I(compressionCbrBitrateOggEnc, 16)
590 LAMEXP_MAKE_OPTION_I(compressionCbrBitrateOpusEnc, 11)
591 LAMEXP_MAKE_OPTION_I(compressionCbrBitrateWave, 0)
592 LAMEXP_MAKE_OPTION_I(compressionEncoder, 0)
593 LAMEXP_MAKE_OPTION_I(compressionRCModeAacEnc, 0)
594 LAMEXP_MAKE_OPTION_I(compressionRCModeAften, 0)
595 LAMEXP_MAKE_OPTION_I(compressionRCModeDcaEnc, 2)
596 LAMEXP_MAKE_OPTION_I(compressionRCModeFLAC, 0)
597 LAMEXP_MAKE_OPTION_I(compressionRCModeLAME, 0)
598 LAMEXP_MAKE_OPTION_I(compressionRCModeMacEnc, 0)
599 LAMEXP_MAKE_OPTION_I(compressionRCModeOggEnc, 0)
600 LAMEXP_MAKE_OPTION_I(compressionRCModeOpusEnc, 0)
601 LAMEXP_MAKE_OPTION_I(compressionRCModeWave, 2)
602 LAMEXP_MAKE_OPTION_I(compressionVbrQualityAacEnc, 10)
603 LAMEXP_MAKE_OPTION_I(compressionVbrQualityAften, 15)
604 LAMEXP_MAKE_OPTION_I(compressionVbrQualityDcaEnc, 13)
605 LAMEXP_MAKE_OPTION_I(compressionVbrQualityFLAC, 5)
606 LAMEXP_MAKE_OPTION_I(compressionVbrQualityLAME, 7)
607 LAMEXP_MAKE_OPTION_I(compressionVbrQualityMacEnc, 2)
608 LAMEXP_MAKE_OPTION_I(compressionVbrQualityOggEnc, 7)
609 LAMEXP_MAKE_OPTION_I(compressionVbrQualityOpusEnc, 11)
610 LAMEXP_MAKE_OPTION_I(compressionVbrQualityWave, 0)
611 LAMEXP_MAKE_OPTION_B(createPlaylist, true)
612 LAMEXP_MAKE_OPTION_S(currentLanguage, defaultLanguage())
613 LAMEXP_MAKE_OPTION_S(currentLanguageFile, QString())
614 LAMEXP_MAKE_OPTION_S(customParametersAacEnc, QString())
615 LAMEXP_MAKE_OPTION_S(customParametersAften, QString())
616 LAMEXP_MAKE_OPTION_S(customParametersDcaEnc, QString())
617 LAMEXP_MAKE_OPTION_S(customParametersFLAC, QString())
618 LAMEXP_MAKE_OPTION_S(customParametersLAME, QString())
619 LAMEXP_MAKE_OPTION_S(customParametersMacEnc, QString())
620 LAMEXP_MAKE_OPTION_S(customParametersOggEnc, QString())
621 LAMEXP_MAKE_OPTION_S(customParametersOpusEnc, QString())
622 LAMEXP_MAKE_OPTION_S(customParametersWave, QString())
623 LAMEXP_MAKE_OPTION_S(customTempPath, QDesktopServices::storageLocation(QDesktopServices::TempLocation))
624 LAMEXP_MAKE_OPTION_B(customTempPathEnabled, false)
625 LAMEXP_MAKE_OPTION_B(dropBoxWidgetEnabled, true)
626 LAMEXP_MAKE_OPTION_I(dropBoxWidgetPositionX, -1)
627 LAMEXP_MAKE_OPTION_I(dropBoxWidgetPositionY, -1)
628 LAMEXP_MAKE_OPTION_S(favoriteOutputFolders, QString())
629 LAMEXP_MAKE_OPTION_B(forceStereoDownmix, false)
630 LAMEXP_MAKE_OPTION_B(hibernateComputer, false)
631 LAMEXP_MAKE_OPTION_I(interfaceStyle, 0)
632 LAMEXP_MAKE_OPTION_I(lameAlgoQuality, 2)
633 LAMEXP_MAKE_OPTION_I(lameChannelMode, 0)
634 LAMEXP_MAKE_OPTION_I(licenseAccepted, 0)
635 LAMEXP_MAKE_OPTION_U(maximumInstances, 0)
636 LAMEXP_MAKE_OPTION_U(metaInfoPosition, UINT_MAX)
637 LAMEXP_MAKE_OPTION_S(mostRecentInputPath, defaultDirectory())
638 LAMEXP_MAKE_OPTION_B(neroAACEnable2Pass, true)
639 LAMEXP_MAKE_OPTION_B(neroAacNotificationsEnabled, true)
640 LAMEXP_MAKE_OPTION_B(normalizationFilterEnabled, false)
641 LAMEXP_MAKE_OPTION_I(normalizationFilterEQMode, 0)
642 LAMEXP_MAKE_OPTION_I(normalizationFilterMaxVolume, -50)
643 LAMEXP_MAKE_OPTION_I(opusComplexity, 10)
644 LAMEXP_MAKE_OPTION_B(opusDisableResample, false)
645 LAMEXP_MAKE_OPTION_I(opusFramesize, 3)
646 LAMEXP_MAKE_OPTION_I(opusOptimizeFor, 0)
647 LAMEXP_MAKE_OPTION_S(outputDir, defaultDirectory())
648 LAMEXP_MAKE_OPTION_B(outputToSourceDir, false)
649 LAMEXP_MAKE_OPTION_I(overwriteMode, Overwrite_KeepBoth)
650 LAMEXP_MAKE_OPTION_B(prependRelativeSourcePath, false)
651 LAMEXP_MAKE_OPTION_B(renameOutputFilesEnabled, false)
652 LAMEXP_MAKE_OPTION_S(renameOutputFilesPattern, "[<TrackNo>] <Artist> - <Title>")
653 LAMEXP_MAKE_OPTION_I(samplingRate, 0)
654 LAMEXP_MAKE_OPTION_B(shellIntegrationEnabled, !lamexp_version_portable())
655 LAMEXP_MAKE_OPTION_B(slowStartup, false)
656 LAMEXP_MAKE_OPTION_B(soundsEnabled, true)
657 LAMEXP_MAKE_OPTION_I(toneAdjustBass, 0)
658 LAMEXP_MAKE_OPTION_I(toneAdjustTreble, 0)
659 LAMEXP_MAKE_OPTION_B(writeMetaTags, true)