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 return setEntry(name, &group, true, false);
831 bool Settings::setGroupDefault(const std::string &name, Settings *group)
833 return setEntry(name, &group, true, true);
837 bool Settings::setBool(const std::string &name, bool value)
839 return set(name, value ? "true" : "false");
843 bool Settings::setS16(const std::string &name, s16 value)
845 return set(name, itos(value));
849 bool Settings::setU16(const std::string &name, u16 value)
851 return set(name, itos(value));
855 bool Settings::setS32(const std::string &name, s32 value)
857 return set(name, itos(value));
861 bool Settings::setU64(const std::string &name, u64 value)
863 std::ostringstream os;
865 return set(name, os.str());
869 bool Settings::setFloat(const std::string &name, float value)
871 return set(name, ftos(value));
875 bool Settings::setV2F(const std::string &name, v2f value)
877 std::ostringstream os;
878 os << "(" << value.X << "," << value.Y << ")";
879 return set(name, os.str());
883 bool Settings::setV3F(const std::string &name, v3f value)
885 std::ostringstream os;
886 os << "(" << value.X << "," << value.Y << "," << value.Z << ")";
887 return set(name, os.str());
891 bool Settings::setFlagStr(const std::string &name, u32 flags,
892 const FlagDesc *flagdesc, u32 flagmask)
895 if (!(flagdesc = getFlagDescFallback(name)))
896 return false; // Not found
899 return set(name, writeFlagString(flags, flagdesc, flagmask));
903 bool Settings::setStruct(const std::string &name, const std::string &format,
906 std::string structstr;
907 if (!serializeStructToString(&structstr, format, value))
910 return set(name, structstr);
914 bool Settings::setNoiseParams(const std::string &name,
915 const NoiseParams &np, bool set_default)
917 Settings *group = new Settings;
919 group->setFloat("offset", np.offset);
920 group->setFloat("scale", np.scale);
921 group->setV3F("spread", np.spread);
922 group->setS32("seed", np.seed);
923 group->setU16("octaves", np.octaves);
924 group->setFloat("persistence", np.persist);
925 group->setFloat("lacunarity", np.lacunarity);
926 group->setFlagStr("flags", np.flags, flagdesc_noiseparams, np.flags);
928 return setEntry(name, &group, true, set_default);
932 bool Settings::remove(const std::string &name)
934 // Lock as short as possible, unlock before doCallbacks()
937 SettingEntries::iterator it = m_settings.find(name);
938 if (it != m_settings.end()) {
939 delete it->second.group;
940 m_settings.erase(it);
952 void Settings::clear()
954 MutexAutoLock lock(m_mutex);
958 void Settings::clearDefaults()
960 MutexAutoLock lock(m_mutex);
961 clearDefaultsNoLock();
964 void Settings::updateValue(const Settings &other, const std::string &name)
969 MutexAutoLock lock(m_mutex);
972 m_settings[name] = other.get(name);
973 } catch (SettingNotFoundException &e) {
978 void Settings::update(const Settings &other)
983 MutexAutoLock lock(m_mutex);
984 MutexAutoLock lock2(other.m_mutex);
990 SettingsParseEvent Settings::parseConfigObject(const std::string &line,
991 const std::string &end, 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 == end)
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::updateNoLock(const Settings &other)
1020 m_settings.insert(other.m_settings.begin(), other.m_settings.end());
1021 m_defaults.insert(other.m_defaults.begin(), other.m_defaults.end());
1025 void Settings::clearNoLock()
1028 for (SettingEntries::const_iterator it = m_settings.begin();
1029 it != m_settings.end(); ++it)
1030 delete it->second.group;
1033 clearDefaultsNoLock();
1036 void Settings::clearDefaultsNoLock()
1038 for (SettingEntries::const_iterator it = m_defaults.begin();
1039 it != m_defaults.end(); ++it)
1040 delete it->second.group;
1044 void Settings::setDefault(const std::string &name, const FlagDesc *flagdesc,
1047 m_flags[name] = flagdesc;
1048 setDefault(name, writeFlagString(flags, flagdesc, U32_MAX));
1051 const FlagDesc *Settings::getFlagDescFallback(const std::string &name) const
1053 auto it = m_flags.find(name);
1054 return it == m_flags.end() ? nullptr : it->second;
1057 void Settings::registerChangedCallback(const std::string &name,
1058 SettingsChangedCallback cbf, void *userdata)
1060 MutexAutoLock lock(m_callback_mutex);
1061 m_callbacks[name].emplace_back(cbf, userdata);
1064 void Settings::deregisterChangedCallback(const std::string &name,
1065 SettingsChangedCallback cbf, void *userdata)
1067 MutexAutoLock lock(m_callback_mutex);
1068 SettingsCallbackMap::iterator it_cbks = m_callbacks.find(name);
1070 if (it_cbks != m_callbacks.end()) {
1071 SettingsCallbackList &cbks = it_cbks->second;
1073 SettingsCallbackList::iterator position =
1074 std::find(cbks.begin(), cbks.end(), std::make_pair(cbf, userdata));
1076 if (position != cbks.end())
1077 cbks.erase(position);
1081 void Settings::doCallbacks(const std::string &name) const
1083 MutexAutoLock lock(m_callback_mutex);
1085 SettingsCallbackMap::const_iterator it_cbks = m_callbacks.find(name);
1086 if (it_cbks != m_callbacks.end()) {
1087 SettingsCallbackList::const_iterator it;
1088 for (it = it_cbks->second.begin(); it != it_cbks->second.end(); ++it)
1089 (it->first)(name, it->second);