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 MutexAutoLock lock(m_mutex);
664 if (m_settings.find(name) != m_settings.end())
666 if (auto parent = getParent())
667 return parent->exists(name);
672 std::vector<std::string> Settings::getNames() const
674 MutexAutoLock lock(m_mutex);
676 std::vector<std::string> names;
677 names.reserve(m_settings.size());
678 for (const auto &settings_it : m_settings) {
679 names.push_back(settings_it.first);
686 /***************************************
687 * Getters that don't throw exceptions *
688 ***************************************/
690 bool Settings::getGroupNoEx(const std::string &name, Settings *&val) const
693 val = getGroup(name);
695 } catch (SettingNotFoundException &e) {
701 bool Settings::getNoEx(const std::string &name, std::string &val) const
706 } catch (SettingNotFoundException &e) {
712 bool Settings::getFlag(const std::string &name) const
715 return getBool(name);
716 } catch(SettingNotFoundException &e) {
722 bool Settings::getFloatNoEx(const std::string &name, float &val) const
725 val = getFloat(name);
727 } catch (SettingNotFoundException &e) {
733 bool Settings::getU16NoEx(const std::string &name, u16 &val) const
738 } catch (SettingNotFoundException &e) {
744 bool Settings::getS16NoEx(const std::string &name, s16 &val) const
749 } catch (SettingNotFoundException &e) {
754 bool Settings::getU32NoEx(const std::string &name, u32 &val) const
759 } catch (SettingNotFoundException &e) {
764 bool Settings::getS32NoEx(const std::string &name, s32 &val) const
769 } catch (SettingNotFoundException &e) {
775 bool Settings::getU64NoEx(const std::string &name, u64 &val) const
780 } catch (SettingNotFoundException &e) {
786 bool Settings::getV2FNoEx(const std::string &name, v2f &val) const
791 } catch (SettingNotFoundException &e) {
797 bool Settings::getV3FNoEx(const std::string &name, v3f &val) const
802 } catch (SettingNotFoundException &e) {
808 bool Settings::getFlagStrNoEx(const std::string &name, u32 &val,
809 const FlagDesc *flagdesc) const
812 if (!(flagdesc = getFlagDescFallback(name)))
813 return false; // Not found
817 val = getFlagStr(name, flagdesc, nullptr);
820 } catch (SettingNotFoundException &e) {
830 bool Settings::setEntry(const std::string &name, const void *data,
833 if (!checkNameValid(name))
835 if (!set_group && !checkValueValid(*(const std::string *)data))
838 Settings *old_group = NULL;
840 MutexAutoLock lock(m_mutex);
842 SettingsEntry &entry = m_settings[name];
843 old_group = entry.group;
845 entry.value = set_group ? "" : *(const std::string *)data;
846 entry.group = set_group ? *(Settings **)data : NULL;
847 entry.is_group = set_group;
849 entry.group->m_end_tag = "}";
858 bool Settings::set(const std::string &name, const std::string &value)
860 if (!setEntry(name, &value, false))
868 // TODO: Remove this function
869 bool Settings::setDefault(const std::string &name, const std::string &value)
871 FATAL_ERROR_IF(m_hierarchy != &g_hierarchy, "setDefault is only valid on "
873 return getLayer(SL_DEFAULTS)->set(name, value);
877 bool Settings::setGroup(const std::string &name, const Settings &group)
879 // Settings must own the group pointer
880 // avoid double-free by copying the source
881 Settings *copy = new Settings();
883 return setEntry(name, ©, true);
887 bool Settings::setBool(const std::string &name, bool value)
889 return set(name, value ? "true" : "false");
893 bool Settings::setS16(const std::string &name, s16 value)
895 return set(name, itos(value));
899 bool Settings::setU16(const std::string &name, u16 value)
901 return set(name, itos(value));
905 bool Settings::setS32(const std::string &name, s32 value)
907 return set(name, itos(value));
911 bool Settings::setU64(const std::string &name, u64 value)
913 std::ostringstream os;
915 return set(name, os.str());
919 bool Settings::setFloat(const std::string &name, float value)
921 return set(name, ftos(value));
925 bool Settings::setV2F(const std::string &name, v2f value)
927 std::ostringstream os;
928 os << "(" << value.X << "," << value.Y << ")";
929 return set(name, os.str());
933 bool Settings::setV3F(const std::string &name, v3f value)
935 std::ostringstream os;
936 os << "(" << value.X << "," << value.Y << "," << value.Z << ")";
937 return set(name, os.str());
941 bool Settings::setFlagStr(const std::string &name, u32 flags,
942 const FlagDesc *flagdesc, u32 flagmask)
945 if (!(flagdesc = getFlagDescFallback(name)))
946 return false; // Not found
949 return set(name, writeFlagString(flags, flagdesc, flagmask));
953 bool Settings::setNoiseParams(const std::string &name, const NoiseParams &np)
955 Settings *group = new Settings;
957 group->setFloat("offset", np.offset);
958 group->setFloat("scale", np.scale);
959 group->setV3F("spread", np.spread);
960 group->setS32("seed", np.seed);
961 group->setU16("octaves", np.octaves);
962 group->setFloat("persistence", np.persist);
963 group->setFloat("lacunarity", np.lacunarity);
964 group->setFlagStr("flags", np.flags, flagdesc_noiseparams, np.flags);
966 return setEntry(name, &group, true);
970 bool Settings::remove(const std::string &name)
972 // Lock as short as possible, unlock before doCallbacks()
975 SettingEntries::iterator it = m_settings.find(name);
976 if (it != m_settings.end()) {
977 delete it->second.group;
978 m_settings.erase(it);
990 SettingsParseEvent Settings::parseConfigObject(const std::string &line,
991 std::string &name, std::string &value)
993 std::string trimmed_line = trim(line);
995 if (trimmed_line.empty())
997 if (trimmed_line[0] == '#')
999 if (trimmed_line == m_end_tag)
1002 size_t pos = trimmed_line.find('=');
1003 if (pos == std::string::npos)
1006 name = trim(trimmed_line.substr(0, pos));
1007 value = trim(trimmed_line.substr(pos + 1));
1011 if (value == "\"\"\"")
1012 return SPE_MULTILINE;
1018 void Settings::clearNoLock()
1020 for (SettingEntries::const_iterator it = m_settings.begin();
1021 it != m_settings.end(); ++it)
1022 delete it->second.group;
1027 void Settings::setDefault(const std::string &name, const FlagDesc *flagdesc,
1030 s_flags[name] = flagdesc;
1031 setDefault(name, writeFlagString(flags, flagdesc, U32_MAX));
1034 const FlagDesc *Settings::getFlagDescFallback(const std::string &name) const
1036 auto it = s_flags.find(name);
1037 return it == s_flags.end() ? nullptr : it->second;
1040 void Settings::registerChangedCallback(const std::string &name,
1041 SettingsChangedCallback cbf, void *userdata)
1043 MutexAutoLock lock(m_callback_mutex);
1044 m_callbacks[name].emplace_back(cbf, userdata);
1047 void Settings::deregisterChangedCallback(const std::string &name,
1048 SettingsChangedCallback cbf, void *userdata)
1050 MutexAutoLock lock(m_callback_mutex);
1051 SettingsCallbackMap::iterator it_cbks = m_callbacks.find(name);
1053 if (it_cbks != m_callbacks.end()) {
1054 SettingsCallbackList &cbks = it_cbks->second;
1056 SettingsCallbackList::iterator position =
1057 std::find(cbks.begin(), cbks.end(), std::make_pair(cbf, userdata));
1059 if (position != cbks.end())
1060 cbks.erase(position);
1064 void Settings::removeSecureSettings()
1066 for (const auto &name : getNames()) {
1067 if (name.compare(0, 7, "secure.") != 0)
1070 errorstream << "Secure setting " << name
1071 << " isn't allowed, so was ignored."
1077 void Settings::doCallbacks(const std::string &name) const
1079 MutexAutoLock lock(m_callback_mutex);
1081 SettingsCallbackMap::const_iterator it_cbks = m_callbacks.find(name);
1082 if (it_cbks != m_callbacks.end()) {
1083 SettingsCallbackList::const_iterator it;
1084 for (it = it_cbks->second.begin(); it != it_cbks->second.end(); ++it)
1085 (it->first)(name, it->second);