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; // Populated in main()
37 std::string g_settings_path;
39 Settings *Settings::s_layers[SL_TOTAL_COUNT] = {0}; // Zeroed by compiler
40 std::unordered_map<std::string, const FlagDesc *> Settings::s_flags;
43 Settings *Settings::createLayer(SettingsLayer sl, const std::string &end_tag)
45 if ((int)sl < 0 || sl >= SL_TOTAL_COUNT)
46 throw new BaseException("Invalid settings layer");
48 Settings *&pos = s_layers[(size_t)sl];
50 throw new BaseException("Setting layer " + std::to_string(sl) + " already exists");
52 pos = new Settings(end_tag);
53 pos->m_settingslayer = sl;
61 Settings *Settings::getLayer(SettingsLayer sl)
63 sanity_check((int)sl >= 0 && sl < SL_TOTAL_COUNT);
64 return s_layers[(size_t)sl];
70 MutexAutoLock lock(m_mutex);
72 if (m_settingslayer < SL_TOTAL_COUNT)
73 s_layers[(size_t)m_settingslayer] = nullptr;
76 if (m_settingslayer == SL_GLOBAL)
83 Settings & Settings::operator = (const Settings &other)
88 // TODO: Avoid copying Settings objects. Make this private.
89 FATAL_ERROR_IF(m_settingslayer != SL_TOTAL_COUNT && other.m_settingslayer != SL_TOTAL_COUNT,
90 ("Tried to copy unique Setting layer " + std::to_string(m_settingslayer)).c_str());
92 MutexAutoLock lock(m_mutex);
93 MutexAutoLock lock2(other.m_mutex);
96 m_settings = other.m_settings;
97 m_callbacks = other.m_callbacks;
103 bool Settings::checkNameValid(const std::string &name)
105 bool valid = name.find_first_of("=\"{}#") == std::string::npos;
107 valid = std::find_if(name.begin(), name.end(), ::isspace) == name.end();
110 errorstream << "Invalid setting name \"" << name << "\""
118 bool Settings::checkValueValid(const std::string &value)
120 if (value.substr(0, 3) == "\"\"\"" ||
121 value.find("\n\"\"\"") != std::string::npos) {
122 errorstream << "Invalid character sequence '\"\"\"' found in"
123 " setting value!" << std::endl;
129 std::string Settings::getMultiline(std::istream &is, size_t *num_lines)
137 std::getline(is, line);
138 if (line == "\"\"\"")
141 value.push_back('\n');
144 size_t len = value.size();
146 value.erase(len - 1);
155 bool Settings::readConfigFile(const char *filename)
157 std::ifstream is(filename);
161 return parseConfigLines(is);
165 bool Settings::parseConfigLines(std::istream &is)
167 MutexAutoLock lock(m_mutex);
169 std::string line, name, value;
172 std::getline(is, line);
173 SettingsParseEvent event = parseConfigObject(line, name, value);
181 m_settings[name] = SettingsEntry(value);
186 Settings *group = new Settings("}");
187 if (!group->parseConfigLines(is)) {
191 m_settings[name] = SettingsEntry(group);
195 m_settings[name] = SettingsEntry(getMultiline(is));
200 // false (failure) if end tag not found
201 return m_end_tag.empty();
205 void Settings::writeLines(std::ostream &os, u32 tab_depth) const
207 MutexAutoLock lock(m_mutex);
209 for (const auto &setting_it : m_settings)
210 printEntry(os, setting_it.first, setting_it.second, tab_depth);
212 // For groups this must be "}" !
213 if (!m_end_tag.empty()) {
214 for (u32 i = 0; i < tab_depth; i++)
217 os << m_end_tag << "\n";
222 void Settings::printEntry(std::ostream &os, const std::string &name,
223 const SettingsEntry &entry, u32 tab_depth)
225 for (u32 i = 0; i != tab_depth; i++)
228 if (entry.is_group) {
229 os << name << " = {\n";
231 entry.group->writeLines(os, tab_depth + 1);
233 // Closing bracket handled by writeLines
237 if (entry.value.find('\n') != std::string::npos)
238 os << "\"\"\"\n" << entry.value << "\n\"\"\"\n";
240 os << entry.value << "\n";
245 bool Settings::updateConfigObject(std::istream &is, std::ostream &os, u32 tab_depth)
247 SettingEntries::const_iterator it;
248 std::set<std::string> present_entries;
249 std::string line, name, value;
250 bool was_modified = false;
251 bool end_found = false;
253 // Add any settings that exist in the config file with the current value
254 // in the object if existing
255 while (is.good() && !end_found) {
256 std::getline(is, line);
257 SettingsParseEvent event = parseConfigObject(line, name, value);
261 // Skip end tag. Append later.
265 value = getMultiline(is);
268 it = m_settings.find(name);
269 if (it != m_settings.end() &&
270 (it->second.is_group || it->second.value != value)) {
271 printEntry(os, name, it->second, tab_depth);
273 } else if (it == m_settings.end()) {
274 // Remove by skipping
279 if (event == SPE_MULTILINE)
280 os << value << "\n\"\"\"\n";
282 present_entries.insert(name);
285 it = m_settings.find(name);
286 if (it != m_settings.end() && it->second.is_group) {
288 sanity_check(it->second.group != NULL);
289 was_modified |= it->second.group->updateConfigObject(is, os, tab_depth + 1);
290 } else if (it == m_settings.end()) {
291 // Remove by skipping
293 Settings removed_group("}"); // Move 'is' to group end
294 std::stringstream ss;
295 removed_group.updateConfigObject(is, ss, tab_depth + 1);
298 printEntry(os, name, it->second, tab_depth);
301 present_entries.insert(name);
304 os << line << (is.eof() ? "" : "\n");
309 if (!line.empty() && is.eof())
312 // Add any settings in the object that don't exist in the config file yet
313 for (it = m_settings.begin(); it != m_settings.end(); ++it) {
314 if (present_entries.find(it->first) != present_entries.end())
317 printEntry(os, it->first, it->second, tab_depth);
322 if (!m_end_tag.empty()) {
323 os << m_end_tag << "\n";
324 was_modified |= !end_found;
331 bool Settings::updateConfigFile(const char *filename)
333 MutexAutoLock lock(m_mutex);
335 std::ifstream is(filename);
336 std::ostringstream os(std::ios_base::binary);
338 bool was_modified = updateConfigObject(is, os);
344 if (!fs::safeWriteToFile(filename, os.str())) {
345 errorstream << "Error writing configuration file: \""
346 << filename << "\"" << std::endl;
354 bool Settings::parseCommandLine(int argc, char *argv[],
355 std::map<std::string, ValueSpec> &allowed_options)
357 int nonopt_index = 0;
358 for (int i = 1; i < argc; i++) {
359 std::string arg_name = argv[i];
360 if (arg_name.substr(0, 2) != "--") {
361 // If option doesn't start with -, read it in as nonoptX
362 if (arg_name[0] != '-'){
363 std::string name = "nonopt";
364 name += itos(nonopt_index);
369 errorstream << "Invalid command-line parameter \""
370 << arg_name << "\": --<option> expected." << std::endl;
374 std::string name = arg_name.substr(2);
376 std::map<std::string, ValueSpec>::iterator n;
377 n = allowed_options.find(name);
378 if (n == allowed_options.end()) {
379 errorstream << "Unknown command-line parameter \""
380 << arg_name << "\"" << std::endl;
384 ValueType type = n->second.type;
388 if (type == VALUETYPE_FLAG) {
391 if ((i + 1) >= argc) {
392 errorstream << "Invalid command-line parameter \""
393 << name << "\": missing value" << std::endl;
411 Settings *Settings::getParent() const
413 // If the Settings object is within the hierarchy structure,
414 // iterate towards the origin (0) to find the next fallback layer
415 if (m_settingslayer >= SL_TOTAL_COUNT)
418 for (int i = (int)m_settingslayer - 1; i >= 0; --i) {
428 const SettingsEntry &Settings::getEntry(const std::string &name) const
431 MutexAutoLock lock(m_mutex);
433 SettingEntries::const_iterator n;
434 if ((n = m_settings.find(name)) != m_settings.end())
438 if (auto parent = getParent())
439 return parent->getEntry(name);
441 throw SettingNotFoundException("Setting [" + name + "] not found.");
445 Settings *Settings::getGroup(const std::string &name) const
447 const SettingsEntry &entry = getEntry(name);
449 throw SettingNotFoundException("Setting [" + name + "] is not a group.");
454 const std::string &Settings::get(const std::string &name) const
456 const SettingsEntry &entry = getEntry(name);
458 throw SettingNotFoundException("Setting [" + name + "] is a group.");
463 bool Settings::getBool(const std::string &name) const
465 return is_yes(get(name));
469 u16 Settings::getU16(const std::string &name) const
471 return stoi(get(name), 0, 65535);
475 s16 Settings::getS16(const std::string &name) const
477 return stoi(get(name), -32768, 32767);
481 u32 Settings::getU32(const std::string &name) const
483 return (u32) stoi(get(name));
486 s32 Settings::getS32(const std::string &name) const
488 return stoi(get(name));
492 float Settings::getFloat(const std::string &name) const
494 return stof(get(name));
498 u64 Settings::getU64(const std::string &name) const
501 std::string s = get(name);
502 std::istringstream ss(s);
508 v2f Settings::getV2F(const std::string &name) const
513 value.X = stof(f.next(","));
514 value.Y = stof(f.next(")"));
519 v3f Settings::getV3F(const std::string &name) const
524 value.X = stof(f.next(","));
525 value.Y = stof(f.next(","));
526 value.Z = stof(f.next(")"));
531 u32 Settings::getFlagStr(const std::string &name, const FlagDesc *flagdesc,
536 // Read default value (if there is any)
537 if (auto parent = getParent())
538 flags = parent->getFlagStr(name, flagdesc, flagmask);
540 // Apply custom flags "on top"
541 if (m_settings.find(name) != m_settings.end()) {
542 std::string value = get(name);
544 u32 mask_user = U32_MAX;
545 flags_user = std::isdigit(value[0])
546 ? stoi(value) // Override default
547 : readFlagString(value, flagdesc, &mask_user);
552 *flagmask |= mask_user;
559 bool Settings::getNoiseParams(const std::string &name, NoiseParams &np) const
561 if (getNoiseParamsFromGroup(name, np) || getNoiseParamsFromValue(name, np))
563 if (auto parent = getParent())
564 return parent->getNoiseParams(name, np);
570 bool Settings::getNoiseParamsFromValue(const std::string &name,
571 NoiseParams &np) const
575 if (!getNoEx(name, value))
578 // Format: f32,f32,(f32,f32,f32),s32,s32,f32[,f32]
581 np.offset = stof(f.next(","));
582 np.scale = stof(f.next(","));
584 np.spread.X = stof(f.next(","));
585 np.spread.Y = stof(f.next(","));
586 np.spread.Z = stof(f.next(")"));
588 np.seed = stoi(f.next(","));
589 np.octaves = stoi(f.next(","));
590 np.persist = stof(f.next(","));
592 std::string optional_params = f.next("");
593 if (!optional_params.empty())
594 np.lacunarity = stof(optional_params);
600 bool Settings::getNoiseParamsFromGroup(const std::string &name,
601 NoiseParams &np) const
603 Settings *group = NULL;
605 if (!getGroupNoEx(name, group))
608 group->getFloatNoEx("offset", np.offset);
609 group->getFloatNoEx("scale", np.scale);
610 group->getV3FNoEx("spread", np.spread);
611 group->getS32NoEx("seed", np.seed);
612 group->getU16NoEx("octaves", np.octaves);
613 group->getFloatNoEx("persistence", np.persist);
614 group->getFloatNoEx("lacunarity", np.lacunarity);
617 if (!group->getFlagStrNoEx("flags", np.flags, flagdesc_noiseparams))
618 np.flags = NOISE_FLAG_DEFAULTS;
624 bool Settings::exists(const std::string &name) const
626 MutexAutoLock lock(m_mutex);
628 if (m_settings.find(name) != m_settings.end())
630 if (auto parent = getParent())
631 return parent->exists(name);
636 std::vector<std::string> Settings::getNames() const
638 MutexAutoLock lock(m_mutex);
640 std::vector<std::string> names;
641 for (const auto &settings_it : m_settings) {
642 names.push_back(settings_it.first);
649 /***************************************
650 * Getters that don't throw exceptions *
651 ***************************************/
653 bool Settings::getGroupNoEx(const std::string &name, Settings *&val) const
656 val = getGroup(name);
658 } catch (SettingNotFoundException &e) {
664 bool Settings::getNoEx(const std::string &name, std::string &val) const
669 } catch (SettingNotFoundException &e) {
675 bool Settings::getFlag(const std::string &name) const
678 return getBool(name);
679 } catch(SettingNotFoundException &e) {
685 bool Settings::getFloatNoEx(const std::string &name, float &val) const
688 val = getFloat(name);
690 } catch (SettingNotFoundException &e) {
696 bool Settings::getU16NoEx(const std::string &name, u16 &val) const
701 } catch (SettingNotFoundException &e) {
707 bool Settings::getS16NoEx(const std::string &name, s16 &val) const
712 } catch (SettingNotFoundException &e) {
718 bool Settings::getS32NoEx(const std::string &name, s32 &val) const
723 } catch (SettingNotFoundException &e) {
729 bool Settings::getU64NoEx(const std::string &name, u64 &val) const
734 } catch (SettingNotFoundException &e) {
740 bool Settings::getV2FNoEx(const std::string &name, v2f &val) const
745 } catch (SettingNotFoundException &e) {
751 bool Settings::getV3FNoEx(const std::string &name, v3f &val) const
756 } catch (SettingNotFoundException &e) {
762 bool Settings::getFlagStrNoEx(const std::string &name, u32 &val,
763 const FlagDesc *flagdesc) const
766 if (!(flagdesc = getFlagDescFallback(name)))
767 return false; // Not found
771 val = getFlagStr(name, flagdesc, nullptr);
774 } catch (SettingNotFoundException &e) {
784 bool Settings::setEntry(const std::string &name, const void *data,
787 if (!checkNameValid(name))
789 if (!set_group && !checkValueValid(*(const std::string *)data))
792 Settings *old_group = NULL;
794 MutexAutoLock lock(m_mutex);
796 SettingsEntry &entry = m_settings[name];
797 old_group = entry.group;
799 entry.value = set_group ? "" : *(const std::string *)data;
800 entry.group = set_group ? *(Settings **)data : NULL;
801 entry.is_group = set_group;
803 entry.group->m_end_tag = "}";
812 bool Settings::set(const std::string &name, const std::string &value)
814 if (!setEntry(name, &value, false))
822 // TODO: Remove this function
823 bool Settings::setDefault(const std::string &name, const std::string &value)
825 return getLayer(SL_DEFAULTS)->set(name, value);
829 bool Settings::setGroup(const std::string &name, const Settings &group)
831 // Settings must own the group pointer
832 // avoid double-free by copying the source
833 Settings *copy = new Settings();
835 return setEntry(name, ©, true);
839 bool Settings::setBool(const std::string &name, bool value)
841 return set(name, value ? "true" : "false");
845 bool Settings::setS16(const std::string &name, s16 value)
847 return set(name, itos(value));
851 bool Settings::setU16(const std::string &name, u16 value)
853 return set(name, itos(value));
857 bool Settings::setS32(const std::string &name, s32 value)
859 return set(name, itos(value));
863 bool Settings::setU64(const std::string &name, u64 value)
865 std::ostringstream os;
867 return set(name, os.str());
871 bool Settings::setFloat(const std::string &name, float value)
873 return set(name, ftos(value));
877 bool Settings::setV2F(const std::string &name, v2f value)
879 std::ostringstream os;
880 os << "(" << value.X << "," << value.Y << ")";
881 return set(name, os.str());
885 bool Settings::setV3F(const std::string &name, v3f value)
887 std::ostringstream os;
888 os << "(" << value.X << "," << value.Y << "," << value.Z << ")";
889 return set(name, os.str());
893 bool Settings::setFlagStr(const std::string &name, u32 flags,
894 const FlagDesc *flagdesc, u32 flagmask)
897 if (!(flagdesc = getFlagDescFallback(name)))
898 return false; // Not found
901 return set(name, writeFlagString(flags, flagdesc, flagmask));
905 bool Settings::setNoiseParams(const std::string &name, const NoiseParams &np)
907 Settings *group = new Settings;
909 group->setFloat("offset", np.offset);
910 group->setFloat("scale", np.scale);
911 group->setV3F("spread", np.spread);
912 group->setS32("seed", np.seed);
913 group->setU16("octaves", np.octaves);
914 group->setFloat("persistence", np.persist);
915 group->setFloat("lacunarity", np.lacunarity);
916 group->setFlagStr("flags", np.flags, flagdesc_noiseparams, np.flags);
918 return setEntry(name, &group, true);
922 bool Settings::remove(const std::string &name)
924 // Lock as short as possible, unlock before doCallbacks()
927 SettingEntries::iterator it = m_settings.find(name);
928 if (it != m_settings.end()) {
929 delete it->second.group;
930 m_settings.erase(it);
942 SettingsParseEvent Settings::parseConfigObject(const std::string &line,
943 std::string &name, std::string &value)
945 std::string trimmed_line = trim(line);
947 if (trimmed_line.empty())
949 if (trimmed_line[0] == '#')
951 if (trimmed_line == m_end_tag)
954 size_t pos = trimmed_line.find('=');
955 if (pos == std::string::npos)
958 name = trim(trimmed_line.substr(0, pos));
959 value = trim(trimmed_line.substr(pos + 1));
963 if (value == "\"\"\"")
964 return SPE_MULTILINE;
970 void Settings::clearNoLock()
972 for (SettingEntries::const_iterator it = m_settings.begin();
973 it != m_settings.end(); ++it)
974 delete it->second.group;
979 void Settings::setDefault(const std::string &name, const FlagDesc *flagdesc,
982 s_flags[name] = flagdesc;
983 setDefault(name, writeFlagString(flags, flagdesc, U32_MAX));
986 const FlagDesc *Settings::getFlagDescFallback(const std::string &name) const
988 auto it = s_flags.find(name);
989 return it == s_flags.end() ? nullptr : it->second;
992 void Settings::registerChangedCallback(const std::string &name,
993 SettingsChangedCallback cbf, void *userdata)
995 MutexAutoLock lock(m_callback_mutex);
996 m_callbacks[name].emplace_back(cbf, userdata);
999 void Settings::deregisterChangedCallback(const std::string &name,
1000 SettingsChangedCallback cbf, void *userdata)
1002 MutexAutoLock lock(m_callback_mutex);
1003 SettingsCallbackMap::iterator it_cbks = m_callbacks.find(name);
1005 if (it_cbks != m_callbacks.end()) {
1006 SettingsCallbackList &cbks = it_cbks->second;
1008 SettingsCallbackList::iterator position =
1009 std::find(cbks.begin(), cbks.end(), std::make_pair(cbf, userdata));
1011 if (position != cbks.end())
1012 cbks.erase(position);
1016 void Settings::removeSecureSettings()
1018 for (const auto &name : getNames()) {
1019 if (name.compare(0, 7, "secure.") != 0)
1022 errorstream << "Secure setting " << name
1023 << " isn't allowed, so was ignored."
1029 void Settings::doCallbacks(const std::string &name) const
1031 MutexAutoLock lock(m_callback_mutex);
1033 SettingsCallbackMap::const_iterator it_cbks = m_callbacks.find(name);
1034 if (it_cbks != m_callbacks.end()) {
1035 SettingsCallbackList::const_iterator it;
1036 for (it = it_cbks->second.begin(); it != it_cbks->second.end(); ++it)
1037 (it->first)(name, it->second);