3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 #include "irrlichttypes_bloated.h"
22 #include "exceptions.h"
23 #include "threading/mutex_auto_lock.h"
24 #include "util/numeric.h" // rangelim
25 #include "util/strfnd.h"
31 #include "util/serialize.h"
37 Settings *g_settings = nullptr;
38 static SettingsHierarchy g_hierarchy;
39 std::string g_settings_path;
41 std::unordered_map<std::string, const FlagDesc *> Settings::s_flags;
43 /* Settings hierarchy implementation */
45 SettingsHierarchy::SettingsHierarchy(Settings *fallback)
47 layers.push_back(fallback);
51 Settings *SettingsHierarchy::getLayer(int layer) const
53 if (layer < 0 || layer >= (int)layers.size())
54 throw BaseException("Invalid settings layer");
59 Settings *SettingsHierarchy::getParent(int layer) const
61 assert(layer >= 0 && layer < (int)layers.size());
62 // iterate towards the origin (0) to find the next fallback layer
63 for (int i = layer - 1; i >= 0; --i) {
72 void SettingsHierarchy::onLayerCreated(int layer, Settings *obj)
75 throw BaseException("Invalid settings layer");
76 if ((int)layers.size() < layer + 1)
77 layers.resize(layer + 1);
79 Settings *&pos = layers[layer];
81 throw BaseException("Setting layer " + itos(layer) + " already exists");
85 if (this == &g_hierarchy && layer == (int)SL_GLOBAL)
90 void SettingsHierarchy::onLayerRemoved(int layer)
92 assert(layer >= 0 && layer < (int)layers.size());
93 layers[layer] = nullptr;
94 if (this == &g_hierarchy && layer == (int)SL_GLOBAL)
98 /* Settings implementation */
100 Settings *Settings::createLayer(SettingsLayer sl, const std::string &end_tag)
102 return new Settings(end_tag, &g_hierarchy, (int)sl);
106 Settings *Settings::getLayer(SettingsLayer sl)
108 return g_hierarchy.getLayer(sl);
112 Settings::Settings(const std::string &end_tag, SettingsHierarchy *h,
113 int settings_layer) :
116 m_settingslayer(settings_layer)
119 m_hierarchy->onLayerCreated(m_settingslayer, this);
123 Settings::~Settings()
125 MutexAutoLock lock(m_mutex);
128 m_hierarchy->onLayerRemoved(m_settingslayer);
134 Settings & Settings::operator = (const Settings &other)
139 // TODO: Avoid copying Settings objects. Make this private.
140 FATAL_ERROR_IF(m_hierarchy || other.m_hierarchy,
141 "Cannot copy or overwrite Settings object that belongs to a hierarchy");
143 MutexAutoLock lock(m_mutex);
144 MutexAutoLock lock2(other.m_mutex);
147 m_settings = other.m_settings;
148 m_callbacks = other.m_callbacks;
154 bool Settings::checkNameValid(const std::string &name)
156 bool valid = name.find_first_of("=\"{}#") == std::string::npos;
158 valid = std::find_if(name.begin(), name.end(), ::isspace) == name.end();
161 errorstream << "Invalid setting name \"" << name << "\""
169 bool Settings::checkValueValid(const std::string &value)
171 if (value.substr(0, 3) == "\"\"\"" ||
172 value.find("\n\"\"\"") != std::string::npos) {
173 errorstream << "Invalid character sequence '\"\"\"' found in"
174 " setting value!" << std::endl;
180 std::string Settings::getMultiline(std::istream &is, size_t *num_lines)
188 std::getline(is, line);
189 if (line == "\"\"\"")
192 value.push_back('\n');
195 size_t len = value.size();
197 value.erase(len - 1);
206 bool Settings::readConfigFile(const char *filename)
208 std::ifstream is(filename);
212 return parseConfigLines(is);
216 bool Settings::parseConfigLines(std::istream &is)
218 MutexAutoLock lock(m_mutex);
220 std::string line, name, value;
223 std::getline(is, line);
224 SettingsParseEvent event = parseConfigObject(line, name, value);
232 m_settings[name] = SettingsEntry(value);
237 Settings *group = new Settings("}");
238 if (!group->parseConfigLines(is)) {
242 m_settings[name] = SettingsEntry(group);
246 m_settings[name] = SettingsEntry(getMultiline(is));
251 // false (failure) if end tag not found
252 return m_end_tag.empty();
256 void Settings::writeLines(std::ostream &os, u32 tab_depth) const
258 MutexAutoLock lock(m_mutex);
260 for (const auto &setting_it : m_settings)
261 printEntry(os, setting_it.first, setting_it.second, tab_depth);
263 // For groups this must be "}" !
264 if (!m_end_tag.empty()) {
265 for (u32 i = 0; i < tab_depth; i++)
268 os << m_end_tag << "\n";
273 void Settings::printEntry(std::ostream &os, const std::string &name,
274 const SettingsEntry &entry, u32 tab_depth)
276 for (u32 i = 0; i != tab_depth; i++)
279 if (entry.is_group) {
280 os << name << " = {\n";
282 entry.group->writeLines(os, tab_depth + 1);
284 // Closing bracket handled by writeLines
288 if (entry.value.find('\n') != std::string::npos)
289 os << "\"\"\"\n" << entry.value << "\n\"\"\"\n";
291 os << entry.value << "\n";
296 bool Settings::updateConfigObject(std::istream &is, std::ostream &os, u32 tab_depth)
298 SettingEntries::const_iterator it;
299 std::set<std::string> present_entries;
300 std::string line, name, value;
301 bool was_modified = false;
302 bool end_found = false;
304 // Add any settings that exist in the config file with the current value
305 // in the object if existing
306 while (is.good() && !end_found) {
307 std::getline(is, line);
308 SettingsParseEvent event = parseConfigObject(line, name, value);
312 // Skip end tag. Append later.
316 value = getMultiline(is);
319 it = m_settings.find(name);
320 if (it != m_settings.end() &&
321 (it->second.is_group || it->second.value != value)) {
322 printEntry(os, name, it->second, tab_depth);
324 } else if (it == m_settings.end()) {
325 // Remove by skipping
330 if (event == SPE_MULTILINE)
331 os << value << "\n\"\"\"\n";
333 present_entries.insert(name);
336 it = m_settings.find(name);
337 if (it != m_settings.end() && it->second.is_group) {
339 sanity_check(it->second.group != NULL);
340 was_modified |= it->second.group->updateConfigObject(is, os, tab_depth + 1);
341 } else if (it == m_settings.end()) {
342 // Remove by skipping
344 Settings removed_group("}"); // Move 'is' to group end
345 std::stringstream ss;
346 removed_group.updateConfigObject(is, ss, tab_depth + 1);
349 printEntry(os, name, it->second, tab_depth);
352 present_entries.insert(name);
355 os << line << (is.eof() ? "" : "\n");
360 if (!line.empty() && is.eof())
363 // Add any settings in the object that don't exist in the config file yet
364 for (it = m_settings.begin(); it != m_settings.end(); ++it) {
365 if (present_entries.find(it->first) != present_entries.end())
368 printEntry(os, it->first, it->second, tab_depth);
373 if (!m_end_tag.empty()) {
374 os << m_end_tag << "\n";
375 was_modified |= !end_found;
382 bool Settings::updateConfigFile(const char *filename)
384 MutexAutoLock lock(m_mutex);
386 std::ifstream is(filename);
387 std::ostringstream os(std::ios_base::binary);
389 bool was_modified = updateConfigObject(is, os);
395 if (!fs::safeWriteToFile(filename, os.str())) {
396 errorstream << "Error writing configuration file: \""
397 << filename << "\"" << std::endl;
405 bool Settings::parseCommandLine(int argc, char *argv[],
406 std::map<std::string, ValueSpec> &allowed_options)
408 int nonopt_index = 0;
409 for (int i = 1; i < argc; i++) {
410 std::string arg_name = argv[i];
411 if (arg_name.substr(0, 2) != "--") {
412 // If option doesn't start with -, read it in as nonoptX
413 if (arg_name[0] != '-'){
414 std::string name = "nonopt";
415 name += itos(nonopt_index);
420 errorstream << "Invalid command-line parameter \""
421 << arg_name << "\": --<option> expected." << std::endl;
425 std::string name = arg_name.substr(2);
427 std::map<std::string, ValueSpec>::iterator n;
428 n = allowed_options.find(name);
429 if (n == allowed_options.end()) {
430 errorstream << "Unknown command-line parameter \""
431 << arg_name << "\"" << std::endl;
435 ValueType type = n->second.type;
439 if (type == VALUETYPE_FLAG) {
442 if ((i + 1) >= argc) {
443 errorstream << "Invalid command-line parameter \""
444 << name << "\": missing value" << std::endl;
462 Settings *Settings::getParent() const
464 return m_hierarchy ? m_hierarchy->getParent(m_settingslayer) : nullptr;
468 const SettingsEntry &Settings::getEntry(const std::string &name) const
471 MutexAutoLock lock(m_mutex);
473 SettingEntries::const_iterator n;
474 if ((n = m_settings.find(name)) != m_settings.end())
478 if (auto parent = getParent())
479 return parent->getEntry(name);
481 throw SettingNotFoundException("Setting [" + name + "] not found.");
485 Settings *Settings::getGroup(const std::string &name) const
487 const SettingsEntry &entry = getEntry(name);
489 throw SettingNotFoundException("Setting [" + name + "] is not a group.");
494 const std::string &Settings::get(const std::string &name) const
496 const SettingsEntry &entry = getEntry(name);
498 throw SettingNotFoundException("Setting [" + name + "] is a group.");
503 bool Settings::getBool(const std::string &name) const
505 return is_yes(get(name));
509 u16 Settings::getU16(const std::string &name) const
511 return stoi(get(name), 0, 65535);
515 s16 Settings::getS16(const std::string &name) const
517 return stoi(get(name), -32768, 32767);
521 u32 Settings::getU32(const std::string &name) const
523 return (u32) stoi(get(name));
526 s32 Settings::getS32(const std::string &name) const
528 return stoi(get(name));
532 float Settings::getFloat(const std::string &name) const
534 return stof(get(name));
538 float Settings::getFloat(const std::string &name, float min, float max) const
540 float val = stof(get(name));
541 return rangelim(val, min, max);
545 u64 Settings::getU64(const std::string &name) const
547 std::string s = get(name);
548 return from_string<u64>(s);
552 v2f Settings::getV2F(const std::string &name) const
557 value.X = stof(f.next(","));
558 value.Y = stof(f.next(")"));
563 v3f Settings::getV3F(const std::string &name) const
568 value.X = stof(f.next(","));
569 value.Y = stof(f.next(","));
570 value.Z = stof(f.next(")"));
575 u32 Settings::getFlagStr(const std::string &name, const FlagDesc *flagdesc,
580 // Read default value (if there is any)
581 if (auto parent = getParent())
582 flags = parent->getFlagStr(name, flagdesc, flagmask);
584 // Apply custom flags "on top"
585 if (m_settings.find(name) != m_settings.end()) {
586 std::string value = get(name);
588 u32 mask_user = U32_MAX;
589 flags_user = std::isdigit(value[0])
590 ? stoi(value) // Override default
591 : readFlagString(value, flagdesc, &mask_user);
596 *flagmask |= mask_user;
603 bool Settings::getNoiseParams(const std::string &name, NoiseParams &np) const
605 if (getNoiseParamsFromGroup(name, np) || getNoiseParamsFromValue(name, np))
607 if (auto parent = getParent())
608 return parent->getNoiseParams(name, np);
614 bool Settings::getNoiseParamsFromValue(const std::string &name,
615 NoiseParams &np) const
619 if (!getNoEx(name, value))
622 // Format: f32,f32,(f32,f32,f32),s32,s32,f32[,f32]
625 np.offset = stof(f.next(","));
626 np.scale = stof(f.next(","));
628 np.spread.X = stof(f.next(","));
629 np.spread.Y = stof(f.next(","));
630 np.spread.Z = stof(f.next(")"));
632 np.seed = stoi(f.next(","));
633 np.octaves = stoi(f.next(","));
634 np.persist = stof(f.next(","));
636 std::string optional_params = f.next("");
637 if (!optional_params.empty())
638 np.lacunarity = stof(optional_params);
644 bool Settings::getNoiseParamsFromGroup(const std::string &name,
645 NoiseParams &np) const
647 Settings *group = NULL;
649 if (!getGroupNoEx(name, group))
652 group->getFloatNoEx("offset", np.offset);
653 group->getFloatNoEx("scale", np.scale);
654 group->getV3FNoEx("spread", np.spread);
655 group->getS32NoEx("seed", np.seed);
656 group->getU16NoEx("octaves", np.octaves);
657 group->getFloatNoEx("persistence", np.persist);
658 group->getFloatNoEx("lacunarity", np.lacunarity);
661 if (!group->getFlagStrNoEx("flags", np.flags, flagdesc_noiseparams))
662 np.flags = NOISE_FLAG_DEFAULTS;
668 bool Settings::exists(const std::string &name) const
670 if (existsLocal(name))
672 if (auto parent = getParent())
673 return parent->exists(name);
678 bool Settings::existsLocal(const std::string &name) const
680 MutexAutoLock lock(m_mutex);
682 return m_settings.find(name) != m_settings.end();
686 std::vector<std::string> Settings::getNames() const
688 MutexAutoLock lock(m_mutex);
690 std::vector<std::string> names;
691 names.reserve(m_settings.size());
692 for (const auto &settings_it : m_settings) {
693 names.push_back(settings_it.first);
700 /***************************************
701 * Getters that don't throw exceptions *
702 ***************************************/
704 bool Settings::getGroupNoEx(const std::string &name, Settings *&val) const
707 val = getGroup(name);
709 } catch (SettingNotFoundException &e) {
715 bool Settings::getNoEx(const std::string &name, std::string &val) const
720 } catch (SettingNotFoundException &e) {
726 bool Settings::getFlag(const std::string &name) const
729 return getBool(name);
730 } catch(SettingNotFoundException &e) {
736 bool Settings::getFloatNoEx(const std::string &name, float &val) const
739 val = getFloat(name);
741 } catch (SettingNotFoundException &e) {
747 bool Settings::getU16NoEx(const std::string &name, u16 &val) const
752 } catch (SettingNotFoundException &e) {
758 bool Settings::getS16NoEx(const std::string &name, s16 &val) const
763 } catch (SettingNotFoundException &e) {
768 bool Settings::getU32NoEx(const std::string &name, u32 &val) const
773 } catch (SettingNotFoundException &e) {
778 bool Settings::getS32NoEx(const std::string &name, s32 &val) const
783 } catch (SettingNotFoundException &e) {
789 bool Settings::getU64NoEx(const std::string &name, u64 &val) const
794 } catch (SettingNotFoundException &e) {
800 bool Settings::getV2FNoEx(const std::string &name, v2f &val) const
805 } catch (SettingNotFoundException &e) {
811 bool Settings::getV3FNoEx(const std::string &name, v3f &val) const
816 } catch (SettingNotFoundException &e) {
822 bool Settings::getFlagStrNoEx(const std::string &name, u32 &val,
823 const FlagDesc *flagdesc) const
826 if (!(flagdesc = getFlagDescFallback(name)))
827 return false; // Not found
831 val = getFlagStr(name, flagdesc, nullptr);
834 } catch (SettingNotFoundException &e) {
844 bool Settings::setEntry(const std::string &name, const void *data,
847 if (!checkNameValid(name))
849 if (!set_group && !checkValueValid(*(const std::string *)data))
852 Settings *old_group = NULL;
854 MutexAutoLock lock(m_mutex);
856 SettingsEntry &entry = m_settings[name];
857 old_group = entry.group;
859 entry.value = set_group ? "" : *(const std::string *)data;
860 entry.group = set_group ? *(Settings **)data : NULL;
861 entry.is_group = set_group;
863 entry.group->m_end_tag = "}";
872 bool Settings::set(const std::string &name, const std::string &value)
874 if (!setEntry(name, &value, false))
882 // TODO: Remove this function
883 bool Settings::setDefault(const std::string &name, const std::string &value)
885 FATAL_ERROR_IF(m_hierarchy != &g_hierarchy, "setDefault is only valid on "
887 return getLayer(SL_DEFAULTS)->set(name, value);
891 bool Settings::setGroup(const std::string &name, const Settings &group)
893 // Settings must own the group pointer
894 // avoid double-free by copying the source
895 Settings *copy = new Settings();
897 return setEntry(name, ©, true);
901 bool Settings::setBool(const std::string &name, bool value)
903 return set(name, value ? "true" : "false");
907 bool Settings::setS16(const std::string &name, s16 value)
909 return set(name, itos(value));
913 bool Settings::setU16(const std::string &name, u16 value)
915 return set(name, itos(value));
919 bool Settings::setS32(const std::string &name, s32 value)
921 return set(name, itos(value));
925 bool Settings::setU64(const std::string &name, u64 value)
927 std::ostringstream os;
929 return set(name, os.str());
933 bool Settings::setFloat(const std::string &name, float value)
935 return set(name, ftos(value));
939 bool Settings::setV2F(const std::string &name, v2f value)
941 std::ostringstream os;
942 os << "(" << value.X << "," << value.Y << ")";
943 return set(name, os.str());
947 bool Settings::setV3F(const std::string &name, v3f value)
949 std::ostringstream os;
950 os << "(" << value.X << "," << value.Y << "," << value.Z << ")";
951 return set(name, os.str());
955 bool Settings::setFlagStr(const std::string &name, u32 flags,
956 const FlagDesc *flagdesc, u32 flagmask)
959 if (!(flagdesc = getFlagDescFallback(name)))
960 return false; // Not found
963 return set(name, writeFlagString(flags, flagdesc, flagmask));
967 bool Settings::setNoiseParams(const std::string &name, const NoiseParams &np)
969 Settings *group = new Settings;
971 group->setFloat("offset", np.offset);
972 group->setFloat("scale", np.scale);
973 group->setV3F("spread", np.spread);
974 group->setS32("seed", np.seed);
975 group->setU16("octaves", np.octaves);
976 group->setFloat("persistence", np.persist);
977 group->setFloat("lacunarity", np.lacunarity);
978 group->setFlagStr("flags", np.flags, flagdesc_noiseparams, np.flags);
980 return setEntry(name, &group, true);
984 bool Settings::remove(const std::string &name)
986 // Lock as short as possible, unlock before doCallbacks()
989 SettingEntries::iterator it = m_settings.find(name);
990 if (it != m_settings.end()) {
991 delete it->second.group;
992 m_settings.erase(it);
1004 SettingsParseEvent Settings::parseConfigObject(const std::string &line,
1005 std::string &name, std::string &value)
1007 std::string trimmed_line = trim(line);
1009 if (trimmed_line.empty())
1011 if (trimmed_line[0] == '#')
1013 if (trimmed_line == m_end_tag)
1016 size_t pos = trimmed_line.find('=');
1017 if (pos == std::string::npos)
1020 name = trim(trimmed_line.substr(0, pos));
1021 value = trim(trimmed_line.substr(pos + 1));
1025 if (value == "\"\"\"")
1026 return SPE_MULTILINE;
1032 void Settings::clearNoLock()
1034 for (SettingEntries::const_iterator it = m_settings.begin();
1035 it != m_settings.end(); ++it)
1036 delete it->second.group;
1041 void Settings::setDefault(const std::string &name, const FlagDesc *flagdesc,
1044 s_flags[name] = flagdesc;
1045 setDefault(name, writeFlagString(flags, flagdesc, U32_MAX));
1048 const FlagDesc *Settings::getFlagDescFallback(const std::string &name) const
1050 auto it = s_flags.find(name);
1051 return it == s_flags.end() ? nullptr : it->second;
1054 void Settings::registerChangedCallback(const std::string &name,
1055 SettingsChangedCallback cbf, void *userdata)
1057 MutexAutoLock lock(m_callback_mutex);
1058 m_callbacks[name].emplace_back(cbf, userdata);
1061 void Settings::deregisterChangedCallback(const std::string &name,
1062 SettingsChangedCallback cbf, void *userdata)
1064 MutexAutoLock lock(m_callback_mutex);
1065 SettingsCallbackMap::iterator it_cbks = m_callbacks.find(name);
1067 if (it_cbks != m_callbacks.end()) {
1068 SettingsCallbackList &cbks = it_cbks->second;
1070 SettingsCallbackList::iterator position =
1071 std::find(cbks.begin(), cbks.end(), std::make_pair(cbf, userdata));
1073 if (position != cbks.end())
1074 cbks.erase(position);
1078 void Settings::removeSecureSettings()
1080 for (const auto &name : getNames()) {
1081 if (name.compare(0, 7, "secure.") != 0)
1084 errorstream << "Secure setting " << name
1085 << " isn't allowed, so was ignored."
1091 void Settings::doCallbacks(const std::string &name) const
1093 MutexAutoLock lock(m_callback_mutex);
1095 SettingsCallbackMap::const_iterator it_cbks = m_callbacks.find(name);
1096 if (it_cbks != m_callbacks.end()) {
1097 SettingsCallbackList::const_iterator it;
1098 for (it = it_cbks->second.begin(); it != it_cbks->second.end(); ++it)
1099 (it->first)(name, it->second);