TmpMenu/src/core/settings.cpp
Andreas Maerten 5c6fb1064b refactor!: File Manager (#1633)
* feat(vscode): added launch.json to dbg
* feat(file_manager): Make use of a global instance
* feat(file_manager): Allow for file and folder instances to be empty
* refactor(GlobalsService): Update code of global service (untested)
2023-07-08 17:54:59 +02:00

134 lines
2.4 KiB
C++

#include "settings.hpp"
#include "thread_pool.hpp"
namespace big
{
void menu_settings::destroy()
{
m_running = false;
}
void menu_settings::init(const file& save_file)
{
m_running = true;
m_save_file = save_file;
load();
g_thread_pool->push([this] {
while (m_running)
{
std::this_thread::sleep_for(100ms);
attempt_save();
}
});
}
void menu_settings::attempt_save()
{
const nlohmann::json j = *this;
if (deep_compare(m_options, j, true))
save();
}
bool menu_settings::load()
{
m_default_options = *this;
std::ifstream file(m_save_file.get_path());
if (!m_save_file.exists())
{
write_default_config();
file.open(m_save_file.get_path());
}
try
{
file >> m_options;
file.close();
}
catch (const std::exception&)
{
file.close();
LOG(WARNING) << "Detected corrupt settings, writing default config...";
write_default_config();
return load();
}
const bool should_save = deep_compare(m_options, m_default_options);
try
{
from_json(m_options, *this);
}
catch (const nlohmann::detail::type_error& e)
{
LOG(WARNING) << e.what();
return false;
}
if (should_save)
{
LOG(INFO) << "Updating settings.";
save();
}
return true;
}
bool menu_settings::write_default_config()
{
std::ofstream file(m_save_file.get_path(), std::ios::out | std::ios::trunc);
file << m_default_options.dump(4);
file.close();
return true;
}
bool menu_settings::deep_compare(nlohmann::json& current_settings, const nlohmann::json& default_settings, bool compare_value)
{
bool should_save = false;
for (auto& e : default_settings.items())
{
const std::string& key = e.key();
if (current_settings.count(key) == 0 || (compare_value && current_settings[key] != e.value()))
{
current_settings[key] = e.value();
should_save = true;
}
else if (current_settings[key].is_object() && e.value().is_object())
{
if (deep_compare(current_settings[key], e.value(), compare_value))
should_save = true;
}
else if (!current_settings[key].is_object() && e.value().is_object())
{
current_settings[key] = e.value();
should_save = true;
}
}
return should_save;
}
bool menu_settings::save()
{
std::ofstream file(m_save_file.get_path(), std::ios::out | std::ios::trunc);
nlohmann::json j = *this;
file << j.dump(4);
file.close();
return true;
}
}