More fixes

This commit is contained in:
Ryzerth
2020-09-24 19:36:57 +02:00
parent 51ee02f9da
commit 48a8b04eaa
18 changed files with 372 additions and 252 deletions

View File

@ -1,62 +1,73 @@
#include <config.h>
namespace config {
bool configModified = false;
json config;
bool autoSaveRunning = false;
std::string _path;
std::thread _workerThread;
std::string rootDir;
ConfigManager::ConfigManager() {
void _autoSaveWorker() {
while (autoSaveRunning) {
if (configModified) {
configModified = false;
std::ofstream file(_path.c_str());
file << std::setw(4) << config;
file.close();
spdlog::info("Config saved");
}
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
}
void ConfigManager::setPath(std::string file) {
path = file;
}
void ConfigManager::load(json default, bool lock) {
if (lock) { mtx.lock(); }
if (path == "") {
spdlog::error("Config manager tried to load file with no path specified");
return;
}
if (!std::filesystem::exists(path)) {
spdlog::warn("Config file '{0}' does not exist, creating it", path);
conf = default;
save(false);
}
if (!std::filesystem::is_regular_file(path)) {
spdlog::error("Config file '{0}' isn't a file", path);
return;
}
void load(std::string path) {
if (!std::filesystem::exists(path)) {
spdlog::error("Config file does not exist");
return;
}
if (!std::filesystem::is_regular_file(path)) {
spdlog::error("Config file isn't a file...");
return;
}
_path = path;
std::ifstream file(path.c_str());
file >> config;
file.close();
}
std::ifstream file(path.c_str());
file >> conf;
file.close();
if (lock) { mtx.unlock(); }
}
void startAutoSave() {
if (autoSaveRunning) {
return;
void ConfigManager::save(bool lock) {
if (lock) { mtx.lock(); }
std::ofstream file(path.c_str());
file << conf.dump(4);
file.close();
if (lock) { mtx.unlock(); }
}
void ConfigManager::enableAutoSave() {
autoSaveEnabled = true;
autoSaveThread = std::thread(autoSaveWorker, this);
}
void ConfigManager::disableAutoSave() {
autoSaveEnabled = false;
autoSaveThread.join();
}
void ConfigManager::aquire() {
mtx.lock();
}
void ConfigManager::release(bool changed) {
this->changed |= changed;
mtx.unlock();
}
void ConfigManager::autoSaveWorker(ConfigManager* _this) {
while (_this->autoSaveEnabled) {
if (!_this->mtx.try_lock()) {
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
continue;
}
autoSaveRunning = true;
_workerThread = std::thread(_autoSaveWorker);
}
void stopAutoSave() {
if (!autoSaveRunning) {
return;
if (_this->changed) {
_this->changed = false;
_this->save(false);
}
autoSaveRunning = false;
_workerThread.join();
_this->mtx.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
void setRootDirectory(std::string dir) {
rootDir = dir;
}
std::string getRootDirectory() {
return rootDir;
}
};
}