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/strfnd.h"
30 #include "util/serialize.h"
36 Settings *g_settings = nullptr;
37 static SettingsHierarchy g_hierarchy;
38 std::string g_settings_path;
40 std::unordered_map<std::string, const FlagDesc *> Settings::s_flags;
42 /* Settings hierarchy implementation */
44 SettingsHierarchy::SettingsHierarchy(Settings *fallback)
46 layers.push_back(fallback);
50 Settings *SettingsHierarchy::getLayer(int layer) const
52 if (layer < 0 || layer >= (int)layers.size())
53 throw BaseException("Invalid settings layer");
58 Settings *SettingsHierarchy::getParent(int layer) const
60 assert(layer >= 0 && layer < (int)layers.size());
61 // iterate towards the origin (0) to find the next fallback layer
62 for (int i = layer - 1; i >= 0; --i) {
71 void SettingsHierarchy::onLayerCreated(int layer, Settings *obj)
74 throw BaseException("Invalid settings layer");
75 if ((int)layers.size() < layer + 1)
76 layers.resize(layer + 1);
78 Settings *&pos = layers[layer];
80 throw BaseException("Setting layer " + itos(layer) + " already exists");
84 if (this == &g_hierarchy && layer == (int)SL_GLOBAL)
89 void SettingsHierarchy::onLayerRemoved(int layer)
91 assert(layer >= 0 && layer < (int)layers.size());
92 layers[layer] = nullptr;
93 if (this == &g_hierarchy && layer == (int)SL_GLOBAL)
97 /* Settings implementation */
99 Settings *Settings::createLayer(SettingsLayer sl, const std::string &end_tag)
101 return new Settings(end_tag, &g_hierarchy, (int)sl);
105 Settings *Settings::getLayer(SettingsLayer sl)
107 return g_hierarchy.getLayer(sl);
111 Settings::Settings(const std::string &end_tag, SettingsHierarchy *h,
112 int settings_layer) :
115 m_settingslayer(settings_layer)
118 m_hierarchy->onLayerCreated(m_settingslayer, this);
122 Settings::~Settings()
124 MutexAutoLock lock(m_mutex);
127 m_hierarchy->onLayerRemoved(m_settingslayer);
133 Settings & Settings::operator = (const Settings &other)
138 // TODO: Avoid copying Settings objects. Make this private.
139 FATAL_ERROR_IF(m_hierarchy || other.m_hierarchy,
140 "Cannot copy or overwrite Settings object that belongs to a hierarchy");
142 MutexAutoLock lock(m_mutex);
143 MutexAutoLock lock2(other.m_mutex);
146 m_settings = other.m_settings;
147 m_callbacks = other.m_callbacks;
153 bool Settings::checkNameValid(const std::string &name)
155 bool valid = name.find_first_of("=\"{}#") == std::string::npos;
157 valid = std::find_if(name.begin(), name.end(), ::isspace) == name.end();
160 errorstream << "Invalid setting name \"" << name << "\""
168 bool Settings::checkValueValid(const std::string &value)
170 if (value.substr(0, 3) == "\"\"\"" ||
171 value.find("\n\"\"\"") != std::string::npos) {
172 errorstream << "Invalid character sequence '\"\"\"' found in"
173 " setting value!" << std::endl;
179 std::string Settings::getMultiline(std::istream &is, size_t *num_lines)
187 std::getline(is, line);
188 if (line == "\"\"\"")
191 value.push_back('\n');
194 size_t len = value.size();
196 value.erase(len - 1);
205 bool Settings::readConfigFile(const char *filename)
207 std::ifstream is(filename);
211 return parseConfigLines(is);
215 bool Settings::parseConfigLines(std::istream &is)
217 MutexAutoLock lock(m_mutex);
219 std::string line, name, value;
222 std::getline(is, line);
223 SettingsParseEvent event = parseConfigObject(line, name, value);
231 m_settings[name] = SettingsEntry(value);
236 Settings *group = new Settings("}");
237 if (!group->parseConfigLines(is)) {
241 m_settings[name] = SettingsEntry(group);
245 m_settings[name] = SettingsEntry(getMultiline(is));
250 // false (failure) if end tag not found
251 return m_end_tag.empty();
255 void Settings::writeLines(std::ostream &os, u32 tab_depth) const
257 MutexAutoLock lock(m_mutex);
259 for (const auto &setting_it : m_settings)
260 printEntry(os, setting_it.first, setting_it.second, tab_depth);
262 // For groups this must be "}" !
263 if (!m_end_tag.empty()) {
264 for (u32 i = 0; i < tab_depth; i++)
267 os << m_end_tag << "\n";
272 void Settings::printEntry(std::ostream &os, const std::string &name,
273 const SettingsEntry &entry, u32 tab_depth)
275 for (u32 i = 0; i != tab_depth; i++)
278 if (entry.is_group) {
279 os << name << " = {\n";
281 entry.group->writeLines(os, tab_depth + 1);
283 // Closing bracket handled by writeLines
287 if (entry.value.find('\n') != std::string::npos)
288 os << "\"\"\"\n" << entry.value << "\n\"\"\"\n";
290 os << entry.value << "\n";
295 bool Settings::updateConfigObject(std::istream &is, std::ostream &os, u32 tab_depth)
297 SettingEntries::const_iterator it;
298 std::set<std::string> present_entries;
299 std::string line, name, value;
300 bool was_modified = false;
301 bool end_found = false;
303 // Add any settings that exist in the config file with the current value
304 // in the object if existing
305 while (is.good() && !end_found) {
306 std::getline(is, line);
307 SettingsParseEvent event = parseConfigObject(line, name, value);
311 // Skip end tag. Append later.
315 value = getMultiline(is);
318 it = m_settings.find(name);
319 if (it != m_settings.end() &&
320 (it->second.is_group || it->second.value != value)) {
321 printEntry(os, name, it->second, tab_depth);
323 } else if (it == m_settings.end()) {
324 // Remove by skipping
329 if (event == SPE_MULTILINE)
330 os << value << "\n\"\"\"\n";
332 present_entries.insert(name);
335 it = m_settings.find(name);
336 if (it != m_settings.end() && it->second.is_group) {
338 sanity_check(it->second.group != NULL);
339 was_modified |= it->second.group->updateConfigObject(is, os, tab_depth + 1);
340 } else if (it == m_settings.end()) {
341 // Remove by skipping
343 Settings removed_group("}"); // Move 'is' to group end
344 std::stringstream ss;
345 removed_group.updateConfigObject(is, ss, tab_depth + 1);
348 printEntry(os, name, it->second, tab_depth);
351 present_entries.insert(name);
354 os << line << (is.eof() ? "" : "\n");
359 if (!line.empty() && is.eof())
362 // Add any settings in the object that don't exist in the config file yet
363 for (it = m_settings.begin(); it != m_settings.end(); ++it) {
364 if (present_entries.find(it->first) != present_entries.end())
367 printEntry(os, it->first, it->second, tab_depth);
372 if (!m_end_tag.empty()) {
373 os << m_end_tag << "\n";
374 was_modified |= !end_found;
381 bool Settings::updateConfigFile(const char *filename)
383 MutexAutoLock lock(m_mutex);
385 std::ifstream is(filename);
386 std::ostringstream os(std::ios_base::binary);
388 bool was_modified = updateConfigObject(is, os);
394 if (!fs::safeWriteToFile(filename, os.str())) {
395 errorstream << "Error writing configuration file: \""
396 << filename << "\"" << std::endl;
404 bool Settings::parseCommandLine(int argc, char *argv[],
405 std::map<std::string, ValueSpec> &allowed_options)
407 int nonopt_index = 0;
408 for (int i = 1; i < argc; i++) {
409 std::string arg_name = argv[i];
410 if (arg_name.substr(0, 2) != "--") {
411 // If option doesn't start with -, read it in as nonoptX
412 if (arg_name[0] != '-'){
413 std::string name = "nonopt";
414 name += itos(nonopt_index);
419 errorstream << "Invalid command-line parameter \""
420 << arg_name << "\": --<option> expected." << std::endl;
424 std::string name = arg_name.substr(2);
426 std::map<std::string, ValueSpec>::iterator n;
427 n = allowed_options.find(name);
428 if (n == allowed_options.end()) {
429 errorstream << "Unknown command-line parameter \""
430 << arg_name << "\"" << std::endl;
434 ValueType type = n->second.type;
438 if (type == VALUETYPE_FLAG) {
441 if ((i + 1) >= argc) {
442 errorstream << "Invalid command-line parameter \""
443 << name << "\": missing value" << std::endl;
461 Settings *Settings::getParent() const
463 return m_hierarchy ? m_hierarchy->getParent(m_settingslayer) : nullptr;
467 const SettingsEntry &Settings::getEntry(const std::string &name) const
470 MutexAutoLock lock(m_mutex);
472 SettingEntries::const_iterator n;
473 if ((n = m_settings.find(name)) != m_settings.end())
477 if (auto parent = getParent())
478 return parent->getEntry(name);
480 throw SettingNotFoundException("Setting [" + name + "] not found.");
484 Settings *Settings::getGroup(const std::string &name) const
486 const SettingsEntry &entry = getEntry(name);
488 throw SettingNotFoundException("Setting [" + name + "] is not a group.");
493 const std::string &Settings::get(const std::string &name) const
495 const SettingsEntry &entry = getEntry(name);
497 throw SettingNotFoundException("Setting [" + name + "] is a group.");
502 bool Settings::getBool(const std::string &name) const
504 return is_yes(get(name));
508 u16 Settings::getU16(const std::string &name) const
510 return stoi(get(name), 0, 65535);
514 s16 Settings::getS16(const std::string &name) const
516 return stoi(get(name), -32768, 32767);
520 u32 Settings::getU32(const std::string &name) const
522 return (u32) stoi(get(name));
525 s32 Settings::getS32(const std::string &name) const
527 return stoi(get(name));
531 float Settings::getFloat(const std::string &name) const
533 return stof(get(name));
537 u64 Settings::getU64(const std::string &name) const
539 std::string s = get(name);
540 return from_string<u64>(s);
544 v2f Settings::getV2F(const std::string &name) const
549 value.X = stof(f.next(","));
550 value.Y = stof(f.next(")"));
555 v3f Settings::getV3F(const std::string &name) const
560 value.X = stof(f.next(","));
561 value.Y = stof(f.next(","));
562 value.Z = stof(f.next(")"));
567 u32 Settings::getFlagStr(const std::string &name, const FlagDesc *flagdesc,
572 // Read default value (if there is any)
573 if (auto parent = getParent())
574 flags = parent->getFlagStr(name, flagdesc, flagmask);
576 // Apply custom flags "on top"
577 if (m_settings.find(name) != m_settings.end()) {
578 std::string value = get(name);
580 u32 mask_user = U32_MAX;
581 flags_user = std::isdigit(value[0])
582 ? stoi(value) // Override default
583 : readFlagString(value, flagdesc, &mask_user);
588 *flagmask |= mask_user;
595 bool Settings::getNoiseParams(const std::string &name, NoiseParams &np) const
597 if (getNoiseParamsFromGroup(name, np) || getNoiseParamsFromValue(name, np))
599 if (auto parent = getParent())
600 return parent->getNoiseParams(name, np);
606 bool Settings::getNoiseParamsFromValue(const std::string &name,
607 NoiseParams &np) const
611 if (!getNoEx(name, value))
614 // Format: f32,f32,(f32,f32,f32),s32,s32,f32[,f32]
617 np.offset = stof(f.next(","));
618 np.scale = stof(f.next(","));
620 np.spread.X = stof(f.next(","));
621 np.spread.Y = stof(f.next(","));
622 np.spread.Z = stof(f.next(")"));
624 np.seed = stoi(f.next(","));
625 np.octaves = stoi(f.next(","));
626 np.persist = stof(f.next(","));
628 std::string optional_params = f.next("");
629 if (!optional_params.empty())
630 np.lacunarity = stof(optional_params);
636 bool Settings::getNoiseParamsFromGroup(const std::string &name,
637 NoiseParams &np) const
639 Settings *group = NULL;
641 if (!getGroupNoEx(name, group))
644 group->getFloatNoEx("offset", np.offset);
645 group->getFloatNoEx("scale", np.scale);
646 group->getV3FNoEx("spread", np.spread);
647 group->getS32NoEx("seed", np.seed);
648 group->getU16NoEx("octaves", np.octaves);
649 group->getFloatNoEx("persistence", np.persist);
650 group->getFloatNoEx("lacunarity", np.lacunarity);
653 if (!group->getFlagStrNoEx("flags", np.flags, flagdesc_noiseparams))
654 np.flags = NOISE_FLAG_DEFAULTS;
660 bool Settings::exists(const std::string &name) const
662 if (existsLocal(name))
664 if (auto parent = getParent())
665 return parent->exists(name);
670 bool Settings::existsLocal(const std::string &name) const
672 MutexAutoLock lock(m_mutex);
674 return m_settings.find(name) != m_settings.end();
678 std::vector<std::string> Settings::getNames() const
680 MutexAutoLock lock(m_mutex);
682 std::vector<std::string> names;
683 names.reserve(m_settings.size());
684 for (const auto &settings_it : m_settings) {
685 names.push_back(settings_it.first);
692 /***************************************
693 * Getters that don't throw exceptions *
694 ***************************************/
696 bool Settings::getGroupNoEx(const std::string &name, Settings *&val) const
699 val = getGroup(name);
701 } catch (SettingNotFoundException &e) {
707 bool Settings::getNoEx(const std::string &name, std::string &val) const
712 } catch (SettingNotFoundException &e) {
718 bool Settings::getFlag(const std::string &name) const
721 return getBool(name);
722 } catch(SettingNotFoundException &e) {
728 bool Settings::getFloatNoEx(const std::string &name, float &val) const
731 val = getFloat(name);
733 } catch (SettingNotFoundException &e) {
739 bool Settings::getU16NoEx(const std::string &name, u16 &val) const
744 } catch (SettingNotFoundException &e) {
750 bool Settings::getS16NoEx(const std::string &name, s16 &val) const
755 } catch (SettingNotFoundException &e) {
760 bool Settings::getU32NoEx(const std::string &name, u32 &val) const
765 } catch (SettingNotFoundException &e) {
770 bool Settings::getS32NoEx(const std::string &name, s32 &val) const
775 } catch (SettingNotFoundException &e) {
781 bool Settings::getU64NoEx(const std::string &name, u64 &val) const
786 } catch (SettingNotFoundException &e) {
792 bool Settings::getV2FNoEx(const std::string &name, v2f &val) const
797 } catch (SettingNotFoundException &e) {
803 bool Settings::getV3FNoEx(const std::string &name, v3f &val) const
808 } catch (SettingNotFoundException &e) {
814 bool Settings::getFlagStrNoEx(const std::string &name, u32 &val,
815 const FlagDesc *flagdesc) const
818 if (!(flagdesc = getFlagDescFallback(name)))
819 return false; // Not found
823 val = getFlagStr(name, flagdesc, nullptr);
826 } catch (SettingNotFoundException &e) {
836 bool Settings::setEntry(const std::string &name, const void *data,
839 if (!checkNameValid(name))
841 if (!set_group && !checkValueValid(*(const std::string *)data))
844 Settings *old_group = NULL;
846 MutexAutoLock lock(m_mutex);
848 SettingsEntry &entry = m_settings[name];
849 old_group = entry.group;
851 entry.value = set_group ? "" : *(const std::string *)data;
852 entry.group = set_group ? *(Settings **)data : NULL;
853 entry.is_group = set_group;
855 entry.group->m_end_tag = "}";
864 bool Settings::set(const std::string &name, const std::string &value)
866 if (!setEntry(name, &value, false))
874 // TODO: Remove this function
875 bool Settings::setDefault(const std::string &name, const std::string &value)
877 FATAL_ERROR_IF(m_hierarchy != &g_hierarchy, "setDefault is only valid on "
879 return getLayer(SL_DEFAULTS)->set(name, value);
883 bool Settings::setGroup(const std::string &name, const Settings &group)
885 // Settings must own the group pointer
886 // avoid double-free by copying the source
887 Settings *copy = new Settings();
889 return setEntry(name, ©, true);
893 bool Settings::setBool(const std::string &name, bool value)
895 return set(name, value ? "true" : "false");
899 bool Settings::setS16(const std::string &name, s16 value)
901 return set(name, itos(value));
905 bool Settings::setU16(const std::string &name, u16 value)
907 return set(name, itos(value));
911 bool Settings::setS32(const std::string &name, s32 value)
913 return set(name, itos(value));
917 bool Settings::setU64(const std::string &name, u64 value)
919 std::ostringstream os;
921 return set(name, os.str());
925 bool Settings::setFloat(const std::string &name, float value)
927 return set(name, ftos(value));
931 bool Settings::setV2F(const std::string &name, v2f value)
933 std::ostringstream os;
934 os << "(" << value.X << "," << value.Y << ")";
935 return set(name, os.str());
939 bool Settings::setV3F(const std::string &name, v3f value)
941 std::ostringstream os;
942 os << "(" << value.X << "," << value.Y << "," << value.Z << ")";
943 return set(name, os.str());
947 bool Settings::setFlagStr(const std::string &name, u32 flags,
948 const FlagDesc *flagdesc, u32 flagmask)
951 if (!(flagdesc = getFlagDescFallback(name)))
952 return false; // Not found
955 return set(name, writeFlagString(flags, flagdesc, flagmask));
959 bool Settings::setNoiseParams(const std::string &name, const NoiseParams &np)
961 Settings *group = new Settings;
963 group->setFloat("offset", np.offset);
964 group->setFloat("scale", np.scale);
965 group->setV3F("spread", np.spread);
966 group->setS32("seed", np.seed);
967 group->setU16("octaves", np.octaves);
968 group->setFloat("persistence", np.persist);
969 group->setFloat("lacunarity", np.lacunarity);
970 group->setFlagStr("flags", np.flags, flagdesc_noiseparams, np.flags);
972 return setEntry(name, &group, true);
976 bool Settings::remove(const std::string &name)
978 // Lock as short as possible, unlock before doCallbacks()
981 SettingEntries::iterator it = m_settings.find(name);
982 if (it != m_settings.end()) {
983 delete it->second.group;
984 m_settings.erase(it);
996 SettingsParseEvent Settings::parseConfigObject(const std::string &line,
997 std::string &name, std::string &value)
999 std::string trimmed_line = trim(line);
1001 if (trimmed_line.empty())
1003 if (trimmed_line[0] == '#')
1005 if (trimmed_line == m_end_tag)
1008 size_t pos = trimmed_line.find('=');
1009 if (pos == std::string::npos)
1012 name = trim(trimmed_line.substr(0, pos));
1013 value = trim(trimmed_line.substr(pos + 1));
1017 if (value == "\"\"\"")
1018 return SPE_MULTILINE;
1024 void Settings::clearNoLock()
1026 for (SettingEntries::const_iterator it = m_settings.begin();
1027 it != m_settings.end(); ++it)
1028 delete it->second.group;
1033 void Settings::setDefault(const std::string &name, const FlagDesc *flagdesc,
1036 s_flags[name] = flagdesc;
1037 setDefault(name, writeFlagString(flags, flagdesc, U32_MAX));
1040 const FlagDesc *Settings::getFlagDescFallback(const std::string &name) const
1042 auto it = s_flags.find(name);
1043 return it == s_flags.end() ? nullptr : it->second;
1046 void Settings::registerChangedCallback(const std::string &name,
1047 SettingsChangedCallback cbf, void *userdata)
1049 MutexAutoLock lock(m_callback_mutex);
1050 m_callbacks[name].emplace_back(cbf, userdata);
1053 void Settings::deregisterChangedCallback(const std::string &name,
1054 SettingsChangedCallback cbf, void *userdata)
1056 MutexAutoLock lock(m_callback_mutex);
1057 SettingsCallbackMap::iterator it_cbks = m_callbacks.find(name);
1059 if (it_cbks != m_callbacks.end()) {
1060 SettingsCallbackList &cbks = it_cbks->second;
1062 SettingsCallbackList::iterator position =
1063 std::find(cbks.begin(), cbks.end(), std::make_pair(cbf, userdata));
1065 if (position != cbks.end())
1066 cbks.erase(position);
1070 void Settings::removeSecureSettings()
1072 for (const auto &name : getNames()) {
1073 if (name.compare(0, 7, "secure.") != 0)
1076 errorstream << "Secure setting " << name
1077 << " isn't allowed, so was ignored."
1083 void Settings::doCallbacks(const std::string &name) const
1085 MutexAutoLock lock(m_callback_mutex);
1087 SettingsCallbackMap::const_iterator it_cbks = m_callbacks.find(name);
1088 if (it_cbks != m_callbacks.end()) {
1089 SettingsCallbackList::const_iterator it;
1090 for (it = it_cbks->second.begin(); it != it_cbks->second.end(); ++it)
1091 (it->first)(name, it->second);