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 static Settings main_settings;
37 Settings *g_settings = &main_settings;
38 std::string g_settings_path;
46 Settings & Settings::operator += (const Settings &other)
54 Settings & Settings::operator = (const Settings &other)
59 MutexAutoLock lock(m_mutex);
60 MutexAutoLock lock2(other.m_mutex);
69 bool Settings::checkNameValid(const std::string &name)
71 bool valid = name.find_first_of("=\"{}#") == std::string::npos;
73 valid = std::find_if(name.begin(), name.end(), ::isspace) == name.end();
76 errorstream << "Invalid setting name \"" << name << "\""
84 bool Settings::checkValueValid(const std::string &value)
86 if (value.substr(0, 3) == "\"\"\"" ||
87 value.find("\n\"\"\"") != std::string::npos) {
88 errorstream << "Invalid character sequence '\"\"\"' found in"
89 " setting value!" << std::endl;
95 std::string Settings::getMultiline(std::istream &is, size_t *num_lines)
103 std::getline(is, line);
104 if (line == "\"\"\"")
107 value.push_back('\n');
110 size_t len = value.size();
112 value.erase(len - 1);
121 bool Settings::readConfigFile(const char *filename)
123 std::ifstream is(filename);
127 return parseConfigLines(is, "");
131 bool Settings::parseConfigLines(std::istream &is, const std::string &end)
133 MutexAutoLock lock(m_mutex);
135 std::string line, name, value;
138 std::getline(is, line);
139 SettingsParseEvent event = parseConfigObject(line, end, name, value);
147 m_settings[name] = SettingsEntry(value);
152 Settings *group = new Settings;
153 if (!group->parseConfigLines(is, "}")) {
157 m_settings[name] = SettingsEntry(group);
161 m_settings[name] = SettingsEntry(getMultiline(is));
170 void Settings::writeLines(std::ostream &os, u32 tab_depth) const
172 MutexAutoLock lock(m_mutex);
174 for (const auto &setting_it : m_settings)
175 printEntry(os, setting_it.first, setting_it.second, tab_depth);
179 void Settings::printEntry(std::ostream &os, const std::string &name,
180 const SettingsEntry &entry, u32 tab_depth)
182 for (u32 i = 0; i != tab_depth; i++)
185 if (entry.is_group) {
186 os << name << " = {\n";
188 entry.group->writeLines(os, tab_depth + 1);
190 for (u32 i = 0; i != tab_depth; i++)
196 if (entry.value.find('\n') != std::string::npos)
197 os << "\"\"\"\n" << entry.value << "\n\"\"\"\n";
199 os << entry.value << "\n";
204 bool Settings::updateConfigObject(std::istream &is, std::ostream &os,
205 const std::string &end, u32 tab_depth)
207 SettingEntries::const_iterator it;
208 std::set<std::string> present_entries;
209 std::string line, name, value;
210 bool was_modified = false;
211 bool end_found = false;
213 // Add any settings that exist in the config file with the current value
214 // in the object if existing
215 while (is.good() && !end_found) {
216 std::getline(is, line);
217 SettingsParseEvent event = parseConfigObject(line, end, name, value);
221 os << line << (is.eof() ? "" : "\n");
225 value = getMultiline(is);
228 it = m_settings.find(name);
229 if (it != m_settings.end() &&
230 (it->second.is_group || it->second.value != value)) {
231 printEntry(os, name, it->second, tab_depth);
233 } else if (it == m_settings.end()) {
234 // Remove by skipping
239 if (event == SPE_MULTILINE)
240 os << value << "\n\"\"\"\n";
242 present_entries.insert(name);
245 it = m_settings.find(name);
246 if (it != m_settings.end() && it->second.is_group) {
248 sanity_check(it->second.group != NULL);
249 was_modified |= it->second.group->updateConfigObject(is, os,
251 } else if (it == m_settings.end()) {
252 // Remove by skipping
254 Settings removed_group; // Move 'is' to group end
255 std::stringstream ss;
256 removed_group.updateConfigObject(is, ss, "}", tab_depth + 1);
259 printEntry(os, name, it->second, tab_depth);
262 present_entries.insert(name);
265 os << line << (is.eof() ? "" : "\n");
270 // Add any settings in the object that don't exist in the config file yet
271 for (it = m_settings.begin(); it != m_settings.end(); ++it) {
272 if (present_entries.find(it->first) != present_entries.end())
275 printEntry(os, it->first, it->second, tab_depth);
283 bool Settings::updateConfigFile(const char *filename)
285 MutexAutoLock lock(m_mutex);
287 std::ifstream is(filename);
288 std::ostringstream os(std::ios_base::binary);
290 bool was_modified = updateConfigObject(is, os, "");
296 if (!fs::safeWriteToFile(filename, os.str())) {
297 errorstream << "Error writing configuration file: \""
298 << filename << "\"" << std::endl;
306 bool Settings::parseCommandLine(int argc, char *argv[],
307 std::map<std::string, ValueSpec> &allowed_options)
309 int nonopt_index = 0;
310 for (int i = 1; i < argc; i++) {
311 std::string arg_name = argv[i];
312 if (arg_name.substr(0, 2) != "--") {
313 // If option doesn't start with -, read it in as nonoptX
314 if (arg_name[0] != '-'){
315 std::string name = "nonopt";
316 name += itos(nonopt_index);
321 errorstream << "Invalid command-line parameter \""
322 << arg_name << "\": --<option> expected." << std::endl;
326 std::string name = arg_name.substr(2);
328 std::map<std::string, ValueSpec>::iterator n;
329 n = allowed_options.find(name);
330 if (n == allowed_options.end()) {
331 errorstream << "Unknown command-line parameter \""
332 << arg_name << "\"" << std::endl;
336 ValueType type = n->second.type;
340 if (type == VALUETYPE_FLAG) {
343 if ((i + 1) >= argc) {
344 errorstream << "Invalid command-line parameter \""
345 << name << "\": missing value" << std::endl;
364 const SettingsEntry &Settings::getEntry(const std::string &name) const
366 MutexAutoLock lock(m_mutex);
368 SettingEntries::const_iterator n;
369 if ((n = m_settings.find(name)) == m_settings.end()) {
370 if ((n = m_defaults.find(name)) == m_defaults.end())
371 throw SettingNotFoundException("Setting [" + name + "] not found.");
377 const SettingsEntry &Settings::getEntryDefault(const std::string &name) const
379 MutexAutoLock lock(m_mutex);
381 SettingEntries::const_iterator n;
382 if ((n = m_defaults.find(name)) == m_defaults.end()) {
383 throw SettingNotFoundException("Setting [" + name + "] not found.");
389 Settings *Settings::getGroup(const std::string &name) const
391 const SettingsEntry &entry = getEntry(name);
393 throw SettingNotFoundException("Setting [" + name + "] is not a group.");
398 const std::string &Settings::get(const std::string &name) const
400 const SettingsEntry &entry = getEntry(name);
402 throw SettingNotFoundException("Setting [" + name + "] is a group.");
407 const std::string &Settings::getDefault(const std::string &name) const
409 const SettingsEntry &entry = getEntryDefault(name);
411 throw SettingNotFoundException("Setting [" + name + "] is a group.");
416 bool Settings::getBool(const std::string &name) const
418 return is_yes(get(name));
422 u16 Settings::getU16(const std::string &name) const
424 return stoi(get(name), 0, 65535);
428 s16 Settings::getS16(const std::string &name) const
430 return stoi(get(name), -32768, 32767);
434 u32 Settings::getU32(const std::string &name) const
436 return (u32) stoi(get(name));
439 s32 Settings::getS32(const std::string &name) const
441 return stoi(get(name));
445 float Settings::getFloat(const std::string &name) const
447 return stof(get(name));
451 u64 Settings::getU64(const std::string &name) const
454 std::string s = get(name);
455 std::istringstream ss(s);
461 v2f Settings::getV2F(const std::string &name) const
466 value.X = stof(f.next(","));
467 value.Y = stof(f.next(")"));
472 v3f Settings::getV3F(const std::string &name) const
477 value.X = stof(f.next(","));
478 value.Y = stof(f.next(","));
479 value.Z = stof(f.next(")"));
484 u32 Settings::getFlagStr(const std::string &name, const FlagDesc *flagdesc,
488 u32 mask_default = 0;
491 // Read default value (if there is any)
492 if (getDefaultNoEx(name, value)) {
493 flags = std::isdigit(value[0])
495 : readFlagString(value, flagdesc, &mask_default);
498 // Apply custom flags "on top"
501 u32 mask_user = U32_MAX;
502 flags_user = std::isdigit(value[0])
503 ? stoi(value) // Override default
504 : readFlagString(value, flagdesc, &mask_user);
510 *flagmask = mask_default | mask_user;
515 // N.B. if getStruct() is used to read a non-POD aggregate type,
516 // the behavior is undefined.
517 bool Settings::getStruct(const std::string &name, const std::string &format,
518 void *out, size_t olen) const
524 } catch (SettingNotFoundException &e) {
528 if (!deSerializeStringToStruct(valstr, format, out, olen))
535 bool Settings::getNoiseParams(const std::string &name, NoiseParams &np) const
537 return getNoiseParamsFromGroup(name, np) || getNoiseParamsFromValue(name, np);
541 bool Settings::getNoiseParamsFromValue(const std::string &name,
542 NoiseParams &np) const
546 if (!getNoEx(name, value))
551 np.offset = stof(f.next(","));
552 np.scale = stof(f.next(","));
554 np.spread.X = stof(f.next(","));
555 np.spread.Y = stof(f.next(","));
556 np.spread.Z = stof(f.next(")"));
558 np.seed = stoi(f.next(","));
559 np.octaves = stoi(f.next(","));
560 np.persist = stof(f.next(","));
562 std::string optional_params = f.next("");
563 if (!optional_params.empty())
564 np.lacunarity = stof(optional_params);
570 bool Settings::getNoiseParamsFromGroup(const std::string &name,
571 NoiseParams &np) const
573 Settings *group = NULL;
575 if (!getGroupNoEx(name, group))
578 group->getFloatNoEx("offset", np.offset);
579 group->getFloatNoEx("scale", np.scale);
580 group->getV3FNoEx("spread", np.spread);
581 group->getS32NoEx("seed", np.seed);
582 group->getU16NoEx("octaves", np.octaves);
583 group->getFloatNoEx("persistence", np.persist);
584 group->getFloatNoEx("lacunarity", np.lacunarity);
587 if (!group->getFlagStrNoEx("flags", np.flags, flagdesc_noiseparams))
588 np.flags = NOISE_FLAG_DEFAULTS;
594 bool Settings::exists(const std::string &name) const
596 MutexAutoLock lock(m_mutex);
598 return (m_settings.find(name) != m_settings.end() ||
599 m_defaults.find(name) != m_defaults.end());
603 std::vector<std::string> Settings::getNames() const
605 std::vector<std::string> names;
606 for (const auto &settings_it : m_settings) {
607 names.push_back(settings_it.first);
614 /***************************************
615 * Getters that don't throw exceptions *
616 ***************************************/
618 bool Settings::getEntryNoEx(const std::string &name, SettingsEntry &val) const
621 val = getEntry(name);
623 } catch (SettingNotFoundException &e) {
629 bool Settings::getEntryDefaultNoEx(const std::string &name, SettingsEntry &val) const
632 val = getEntryDefault(name);
634 } catch (SettingNotFoundException &e) {
640 bool Settings::getGroupNoEx(const std::string &name, Settings *&val) const
643 val = getGroup(name);
645 } catch (SettingNotFoundException &e) {
651 bool Settings::getNoEx(const std::string &name, std::string &val) const
656 } catch (SettingNotFoundException &e) {
662 bool Settings::getDefaultNoEx(const std::string &name, std::string &val) const
665 val = getDefault(name);
667 } catch (SettingNotFoundException &e) {
673 bool Settings::getFlag(const std::string &name) const
676 return getBool(name);
677 } catch(SettingNotFoundException &e) {
683 bool Settings::getFloatNoEx(const std::string &name, float &val) const
686 val = getFloat(name);
688 } catch (SettingNotFoundException &e) {
694 bool Settings::getU16NoEx(const std::string &name, u16 &val) const
699 } catch (SettingNotFoundException &e) {
705 bool Settings::getS16NoEx(const std::string &name, s16 &val) const
710 } catch (SettingNotFoundException &e) {
716 bool Settings::getS32NoEx(const std::string &name, s32 &val) const
721 } catch (SettingNotFoundException &e) {
727 bool Settings::getU64NoEx(const std::string &name, u64 &val) const
732 } catch (SettingNotFoundException &e) {
738 bool Settings::getV2FNoEx(const std::string &name, v2f &val) const
743 } catch (SettingNotFoundException &e) {
749 bool Settings::getV3FNoEx(const std::string &name, v3f &val) const
754 } catch (SettingNotFoundException &e) {
760 bool Settings::getFlagStrNoEx(const std::string &name, u32 &val,
761 const FlagDesc *flagdesc) const
764 if (!(flagdesc = getFlagDescFallback(name)))
765 return false; // Not found
769 val = getFlagStr(name, flagdesc, nullptr);
772 } catch (SettingNotFoundException &e) {
782 bool Settings::setEntry(const std::string &name, const void *data,
783 bool set_group, bool set_default)
785 Settings *old_group = NULL;
787 if (!checkNameValid(name))
789 if (!set_group && !checkValueValid(*(const std::string *)data))
793 MutexAutoLock lock(m_mutex);
795 SettingsEntry &entry = set_default ? m_defaults[name] : m_settings[name];
796 old_group = entry.group;
798 entry.value = set_group ? "" : *(const std::string *)data;
799 entry.group = set_group ? *(Settings **)data : NULL;
800 entry.is_group = set_group;
809 bool Settings::set(const std::string &name, const std::string &value)
811 if (!setEntry(name, &value, false, false))
819 bool Settings::setDefault(const std::string &name, const std::string &value)
821 return setEntry(name, &value, false, true);
825 bool Settings::setGroup(const std::string &name, Settings *group)
827 // Settings must own the group pointer
828 // avoid double-free by copying the source
829 Settings *copy = new Settings();
831 return setEntry(name, ©, true, false);
835 bool Settings::setGroupDefault(const std::string &name, Settings *group)
837 // Settings must own the group pointer
838 // avoid double-free by copying the source
839 Settings *copy = new Settings();
841 return setEntry(name, ©, true, true);
845 bool Settings::setBool(const std::string &name, bool value)
847 return set(name, value ? "true" : "false");
851 bool Settings::setS16(const std::string &name, s16 value)
853 return set(name, itos(value));
857 bool Settings::setU16(const std::string &name, u16 value)
859 return set(name, itos(value));
863 bool Settings::setS32(const std::string &name, s32 value)
865 return set(name, itos(value));
869 bool Settings::setU64(const std::string &name, u64 value)
871 std::ostringstream os;
873 return set(name, os.str());
877 bool Settings::setFloat(const std::string &name, float value)
879 return set(name, ftos(value));
883 bool Settings::setV2F(const std::string &name, v2f value)
885 std::ostringstream os;
886 os << "(" << value.X << "," << value.Y << ")";
887 return set(name, os.str());
891 bool Settings::setV3F(const std::string &name, v3f value)
893 std::ostringstream os;
894 os << "(" << value.X << "," << value.Y << "," << value.Z << ")";
895 return set(name, os.str());
899 bool Settings::setFlagStr(const std::string &name, u32 flags,
900 const FlagDesc *flagdesc, u32 flagmask)
903 if (!(flagdesc = getFlagDescFallback(name)))
904 return false; // Not found
907 return set(name, writeFlagString(flags, flagdesc, flagmask));
911 bool Settings::setStruct(const std::string &name, const std::string &format,
914 std::string structstr;
915 if (!serializeStructToString(&structstr, format, value))
918 return set(name, structstr);
922 bool Settings::setNoiseParams(const std::string &name,
923 const NoiseParams &np, bool set_default)
925 Settings *group = new Settings;
927 group->setFloat("offset", np.offset);
928 group->setFloat("scale", np.scale);
929 group->setV3F("spread", np.spread);
930 group->setS32("seed", np.seed);
931 group->setU16("octaves", np.octaves);
932 group->setFloat("persistence", np.persist);
933 group->setFloat("lacunarity", np.lacunarity);
934 group->setFlagStr("flags", np.flags, flagdesc_noiseparams, np.flags);
936 return setEntry(name, &group, true, set_default);
940 bool Settings::remove(const std::string &name)
942 // Lock as short as possible, unlock before doCallbacks()
945 SettingEntries::iterator it = m_settings.find(name);
946 if (it != m_settings.end()) {
947 delete it->second.group;
948 m_settings.erase(it);
960 void Settings::clear()
962 MutexAutoLock lock(m_mutex);
966 void Settings::clearDefaults()
968 MutexAutoLock lock(m_mutex);
969 clearDefaultsNoLock();
972 void Settings::updateValue(const Settings &other, const std::string &name)
977 MutexAutoLock lock(m_mutex);
980 m_settings[name] = other.get(name);
981 } catch (SettingNotFoundException &e) {
986 void Settings::update(const Settings &other)
991 MutexAutoLock lock(m_mutex);
992 MutexAutoLock lock2(other.m_mutex);
998 SettingsParseEvent Settings::parseConfigObject(const std::string &line,
999 const std::string &end, std::string &name, std::string &value)
1001 std::string trimmed_line = trim(line);
1003 if (trimmed_line.empty())
1005 if (trimmed_line[0] == '#')
1007 if (trimmed_line == end)
1010 size_t pos = trimmed_line.find('=');
1011 if (pos == std::string::npos)
1014 name = trim(trimmed_line.substr(0, pos));
1015 value = trim(trimmed_line.substr(pos + 1));
1019 if (value == "\"\"\"")
1020 return SPE_MULTILINE;
1026 void Settings::updateNoLock(const Settings &other)
1028 m_settings.insert(other.m_settings.begin(), other.m_settings.end());
1029 m_defaults.insert(other.m_defaults.begin(), other.m_defaults.end());
1033 void Settings::clearNoLock()
1036 for (SettingEntries::const_iterator it = m_settings.begin();
1037 it != m_settings.end(); ++it)
1038 delete it->second.group;
1041 clearDefaultsNoLock();
1044 void Settings::clearDefaultsNoLock()
1046 for (SettingEntries::const_iterator it = m_defaults.begin();
1047 it != m_defaults.end(); ++it)
1048 delete it->second.group;
1052 void Settings::setDefault(const std::string &name, const FlagDesc *flagdesc,
1055 m_flags[name] = flagdesc;
1056 setDefault(name, writeFlagString(flags, flagdesc, U32_MAX));
1059 void Settings::overrideDefaults(Settings *other)
1061 for (const auto &setting : other->m_settings) {
1062 if (setting.second.is_group) {
1063 setGroupDefault(setting.first, setting.second.group);
1066 const FlagDesc *flagdesc = getFlagDescFallback(setting.first);
1068 // Flags cannot be copied directly.
1069 // 1) Get the current set flags
1070 u32 flags = getFlagStr(setting.first, flagdesc, nullptr);
1071 // 2) Set the flags as defaults
1072 other->setDefault(setting.first, flagdesc, flags);
1073 // 3) Get the newly set flags and override the default setting value
1074 setDefault(setting.first, flagdesc,
1075 other->getFlagStr(setting.first, flagdesc, nullptr));
1078 // Also covers FlagDesc settings
1079 setDefault(setting.first, setting.second.value);
1083 const FlagDesc *Settings::getFlagDescFallback(const std::string &name) const
1085 auto it = m_flags.find(name);
1086 return it == m_flags.end() ? nullptr : it->second;
1089 void Settings::registerChangedCallback(const std::string &name,
1090 SettingsChangedCallback cbf, void *userdata)
1092 MutexAutoLock lock(m_callback_mutex);
1093 m_callbacks[name].emplace_back(cbf, userdata);
1096 void Settings::deregisterChangedCallback(const std::string &name,
1097 SettingsChangedCallback cbf, void *userdata)
1099 MutexAutoLock lock(m_callback_mutex);
1100 SettingsCallbackMap::iterator it_cbks = m_callbacks.find(name);
1102 if (it_cbks != m_callbacks.end()) {
1103 SettingsCallbackList &cbks = it_cbks->second;
1105 SettingsCallbackList::iterator position =
1106 std::find(cbks.begin(), cbks.end(), std::make_pair(cbf, userdata));
1108 if (position != cbks.end())
1109 cbks.erase(position);
1113 void Settings::doCallbacks(const std::string &name) const
1115 MutexAutoLock lock(m_callback_mutex);
1117 SettingsCallbackMap::const_iterator it_cbks = m_callbacks.find(name);
1118 if (it_cbks != m_callbacks.end()) {
1119 SettingsCallbackList::const_iterator it;
1120 for (it = it_cbks->second.begin(); it != it_cbks->second.end(); ++it)
1121 (it->first)(name, it->second);