You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

127 lines
2.1 KiB

2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
  1. #include "settings-manager.hpp"
  2. #include <fstream>
  3. using namespace std;
  4. SettingsManager::SettingsManager()
  5. {
  6. settings = list<SettingsEntry*>();
  7. readAll();
  8. }
  9. SettingsManager::~SettingsManager()
  10. {
  11. }
  12. void SettingsManager::Update(string key, string value)
  13. {
  14. for (auto entry : settings)
  15. {
  16. if (entry->key == key)
  17. {
  18. entry->value = value;
  19. return;
  20. }
  21. }
  22. settings.push_back(new SettingsEntry{
  23. .key = key,
  24. .value = value,
  25. });
  26. }
  27. void SettingsManager::UpdateBool(string key, bool value)
  28. {
  29. if (value)
  30. Update(key, "true");
  31. else
  32. Update(key, "false");
  33. }
  34. void SettingsManager::Save(string key, string value)
  35. {
  36. Update(key, value);
  37. SaveAll();
  38. }
  39. void SettingsManager::SaveAll()
  40. {
  41. saveAll();
  42. }
  43. string SettingsManager::Get(string key)
  44. {
  45. for (auto entry : settings)
  46. {
  47. if (entry->key == key)
  48. {
  49. return entry->value;
  50. }
  51. }
  52. return "";
  53. }
  54. string SettingsManager::GetWithDefault(string key, string defaultValue)
  55. {
  56. auto value = Get(key);
  57. if (value == "")
  58. return defaultValue;
  59. return value;
  60. }
  61. bool SettingsManager::GetBool(string key)
  62. {
  63. if (Get(key) == "true")
  64. return true;
  65. return false;
  66. }
  67. bool SettingsManager::GetBoolWithDefault(string key, bool defaultValue)
  68. {
  69. auto value = Get(key);
  70. if (value == "true")
  71. return true;
  72. if (value == "false")
  73. return false;
  74. return defaultValue;
  75. }
  76. void SettingsManager::readAll()
  77. {
  78. settings.clear();
  79. ifstream fin;
  80. string line;
  81. fin.open("./config.cfg", ios::in);
  82. while (getline(fin, line))
  83. {
  84. if (line.find("=") != std::string::npos)
  85. {
  86. settings.push_back(new SettingsEntry{
  87. .key = line.substr(0, line.find("=")),
  88. .value = line.substr(line.find("=")+1, line.length()),
  89. });
  90. }
  91. }
  92. }
  93. void SettingsManager::saveAll()
  94. {
  95. ofstream fout;
  96. fout.open("./config.cfg", ios::trunc);
  97. for (auto entry : settings)
  98. {
  99. fout << entry->key << "=" << entry->value << endl;
  100. }
  101. }