Fine tune translations loading for Chinese locales
[qBittorrent.git] / src / base / settingsstorage.cpp
blob09ee2fc992208c5ff292656503a606bc19c08ae0
1 /*
2 * Bittorrent Client using Qt and libtorrent.
3 * Copyright (C) 2016 Vladimir Golovnev <glassez@yandex.ru>
4 * Copyright (C) 2014 sledgehammer999 <hammered999@gmail.com>
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
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
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * In addition, as a special exception, the copyright holders give permission to
21 * link this program with the OpenSSL project's "OpenSSL" library (or with
22 * modified versions of it that use the same license as the "OpenSSL" library),
23 * and distribute the linked executables. You must obey the GNU General Public
24 * License in all respects for all of the code used other than "OpenSSL". If you
25 * modify file(s), you may extend this exception to your version of the file(s),
26 * but you are not obligated to do so. If you do not wish to do so, delete this
27 * exception statement from your version.
30 #include "settingsstorage.h"
32 #include <chrono>
33 #include <memory>
35 #include <QFile>
36 #include <QHash>
38 #include "global.h"
39 #include "logger.h"
40 #include "path.h"
41 #include "profile.h"
42 #include "utils/fs.h"
44 using namespace std::chrono_literals;
46 SettingsStorage *SettingsStorage::m_instance = nullptr;
48 SettingsStorage::SettingsStorage()
49 : m_nativeSettingsName {u"qBittorrent"_qs}
51 readNativeSettings();
53 m_timer.setSingleShot(true);
54 m_timer.setInterval(5s);
55 connect(&m_timer, &QTimer::timeout, this, &SettingsStorage::save);
58 SettingsStorage::~SettingsStorage()
60 save();
63 void SettingsStorage::initInstance()
65 if (!m_instance)
66 m_instance = new SettingsStorage;
69 void SettingsStorage::freeInstance()
71 delete m_instance;
72 m_instance = nullptr;
75 SettingsStorage *SettingsStorage::instance()
77 return m_instance;
80 bool SettingsStorage::save()
82 const QWriteLocker locker(&m_lock); // guard for `m_dirty` too
83 if (!m_dirty) return true;
85 if (!writeNativeSettings())
87 m_timer.start();
88 return false;
91 m_dirty = false;
92 return true;
95 QVariant SettingsStorage::loadValueImpl(const QString &key, const QVariant &defaultValue) const
97 const QReadLocker locker(&m_lock);
98 return m_data.value(key, defaultValue);
101 void SettingsStorage::storeValueImpl(const QString &key, const QVariant &value)
103 const QWriteLocker locker(&m_lock);
104 QVariant &currentValue = m_data[key];
105 if (currentValue != value)
107 m_dirty = true;
108 currentValue = value;
109 m_timer.start();
113 void SettingsStorage::readNativeSettings()
115 // We return actual file names used by QSettings because
116 // there is no other way to get that name except actually create a QSettings object.
117 // If serialization operation was not successful we return empty string.
118 const auto deserialize = [](QVariantHash &data, const QString &nativeSettingsName) -> Path
120 std::unique_ptr<QSettings> nativeSettings = Profile::instance()->applicationSettings(nativeSettingsName);
121 if (nativeSettings->allKeys().isEmpty())
122 return {};
124 // Copy everything into memory. This means even keys inserted in the file manually
125 // or that we don't touch directly in this code (eg disabled by ifdef). This ensures
126 // that they will be copied over when save our settings to disk.
127 for (const QString &key : asConst(nativeSettings->allKeys()))
129 const QVariant value = nativeSettings->value(key);
130 if (value.isValid())
131 data[key] = value;
134 return Path(nativeSettings->fileName());
137 const Path newPath = deserialize(m_data, (m_nativeSettingsName + u"_new"));
138 if (!newPath.isEmpty())
140 // "_new" file is NOT empty
141 // This means that the PC closed either due to power outage
142 // or because the disk was full. In any case the settings weren't transferred
143 // in their final position. So assume that qbittorrent_new.ini/qbittorrent_new.conf
144 // contains the most recent settings.
145 LogMsg(tr("Detected unclean program exit. Using fallback file to restore settings: %1")
146 .arg(newPath.toString()), Log::WARNING);
148 QString finalPathStr = newPath.data();
149 const int index = finalPathStr.lastIndexOf(u"_new", -1, Qt::CaseInsensitive);
150 finalPathStr.remove(index, 4);
152 const Path finalPath {finalPathStr};
153 Utils::Fs::removeFile(finalPath);
154 Utils::Fs::renameFile(newPath, finalPath);
156 else
158 deserialize(m_data, m_nativeSettingsName);
162 bool SettingsStorage::writeNativeSettings() const
164 std::unique_ptr<QSettings> nativeSettings = Profile::instance()->applicationSettings(m_nativeSettingsName + u"_new");
166 // QSettings deletes the file before writing it out. This can result in problems
167 // if the disk is full or a power outage occurs. Those events might occur
168 // between deleting the file and recreating it. This is a safety measure.
169 // Write everything to qBittorrent_new.ini/qBittorrent_new.conf and if it succeeds
170 // replace qBittorrent.ini/qBittorrent.conf with it.
171 for (auto i = m_data.begin(); i != m_data.end(); ++i)
172 nativeSettings->setValue(i.key(), i.value());
174 nativeSettings->sync(); // Important to get error status
175 const QSettings::Status status = nativeSettings->status();
176 const Path newPath {nativeSettings->fileName()};
178 nativeSettings.reset(); // close QSettings
180 switch (status)
182 case QSettings::NoError:
183 break;
184 case QSettings::AccessError:
185 LogMsg(tr("An access error occurred while trying to write the configuration file."), Log::CRITICAL);
186 break;
187 case QSettings::FormatError:
188 LogMsg(tr("A format error occurred while trying to write the configuration file."), Log::CRITICAL);
189 break;
190 default:
191 LogMsg(tr("An unknown error occurred while trying to write the configuration file."), Log::CRITICAL);
192 break;
195 if (status != QSettings::NoError)
197 Utils::Fs::removeFile(newPath);
198 return false;
201 QString finalPathStr = newPath.data();
202 const int index = finalPathStr.lastIndexOf(u"_new", -1, Qt::CaseInsensitive);
203 finalPathStr.remove(index, 4);
205 const Path finalPath {finalPathStr};
206 Utils::Fs::removeFile(finalPath);
207 return Utils::Fs::renameFile(newPath, finalPath);
210 void SettingsStorage::removeValue(const QString &key)
212 const QWriteLocker locker(&m_lock);
213 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
214 if (m_data.remove(key))
215 #else
216 if (m_data.remove(key) > 0)
217 #endif
219 m_dirty = true;
220 m_timer.start();
224 bool SettingsStorage::hasKey(const QString &key) const
226 const QReadLocker locker {&m_lock};
227 return m_data.contains(key);