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,
487 std::string val = get(name);
488 return std::isdigit(val[0])
490 : readFlagString(val, flagdesc, flagmask);
494 // N.B. if getStruct() is used to read a non-POD aggregate type,
495 // the behavior is undefined.
496 bool Settings::getStruct(const std::string &name, const std::string &format,
497 void *out, size_t olen) const
503 } catch (SettingNotFoundException &e) {
507 if (!deSerializeStringToStruct(valstr, format, out, olen))
514 bool Settings::getNoiseParams(const std::string &name, NoiseParams &np) const
516 return getNoiseParamsFromGroup(name, np) || getNoiseParamsFromValue(name, np);
520 bool Settings::getNoiseParamsFromValue(const std::string &name,
521 NoiseParams &np) const
525 if (!getNoEx(name, value))
530 np.offset = stof(f.next(","));
531 np.scale = stof(f.next(","));
533 np.spread.X = stof(f.next(","));
534 np.spread.Y = stof(f.next(","));
535 np.spread.Z = stof(f.next(")"));
537 np.seed = stoi(f.next(","));
538 np.octaves = stoi(f.next(","));
539 np.persist = stof(f.next(","));
541 std::string optional_params = f.next("");
542 if (!optional_params.empty())
543 np.lacunarity = stof(optional_params);
549 bool Settings::getNoiseParamsFromGroup(const std::string &name,
550 NoiseParams &np) const
552 Settings *group = NULL;
554 if (!getGroupNoEx(name, group))
557 group->getFloatNoEx("offset", np.offset);
558 group->getFloatNoEx("scale", np.scale);
559 group->getV3FNoEx("spread", np.spread);
560 group->getS32NoEx("seed", np.seed);
561 group->getU16NoEx("octaves", np.octaves);
562 group->getFloatNoEx("persistence", np.persist);
563 group->getFloatNoEx("lacunarity", np.lacunarity);
566 if (!group->getFlagStrNoEx("flags", np.flags, flagdesc_noiseparams))
567 np.flags = NOISE_FLAG_DEFAULTS;
573 bool Settings::exists(const std::string &name) const
575 MutexAutoLock lock(m_mutex);
577 return (m_settings.find(name) != m_settings.end() ||
578 m_defaults.find(name) != m_defaults.end());
582 std::vector<std::string> Settings::getNames() const
584 std::vector<std::string> names;
585 for (const auto &settings_it : m_settings) {
586 names.push_back(settings_it.first);
593 /***************************************
594 * Getters that don't throw exceptions *
595 ***************************************/
597 bool Settings::getEntryNoEx(const std::string &name, SettingsEntry &val) const
600 val = getEntry(name);
602 } catch (SettingNotFoundException &e) {
608 bool Settings::getEntryDefaultNoEx(const std::string &name, SettingsEntry &val) const
611 val = getEntryDefault(name);
613 } catch (SettingNotFoundException &e) {
619 bool Settings::getGroupNoEx(const std::string &name, Settings *&val) const
622 val = getGroup(name);
624 } catch (SettingNotFoundException &e) {
630 bool Settings::getNoEx(const std::string &name, std::string &val) const
635 } catch (SettingNotFoundException &e) {
641 bool Settings::getDefaultNoEx(const std::string &name, std::string &val) const
644 val = getDefault(name);
646 } catch (SettingNotFoundException &e) {
652 bool Settings::getFlag(const std::string &name) const
655 return getBool(name);
656 } catch(SettingNotFoundException &e) {
662 bool Settings::getFloatNoEx(const std::string &name, float &val) const
665 val = getFloat(name);
667 } catch (SettingNotFoundException &e) {
673 bool Settings::getU16NoEx(const std::string &name, u16 &val) const
678 } catch (SettingNotFoundException &e) {
684 bool Settings::getS16NoEx(const std::string &name, s16 &val) const
689 } catch (SettingNotFoundException &e) {
695 bool Settings::getS32NoEx(const std::string &name, s32 &val) const
700 } catch (SettingNotFoundException &e) {
706 bool Settings::getU64NoEx(const std::string &name, u64 &val) const
711 } catch (SettingNotFoundException &e) {
717 bool Settings::getV2FNoEx(const std::string &name, v2f &val) const
722 } catch (SettingNotFoundException &e) {
728 bool Settings::getV3FNoEx(const std::string &name, v3f &val) const
733 } catch (SettingNotFoundException &e) {
739 // N.B. getFlagStrNoEx() does not set val, but merely modifies it. Thus,
740 // val must be initialized before using getFlagStrNoEx(). The intention of
741 // this is to simplify modifying a flags field from a default value.
742 bool Settings::getFlagStrNoEx(const std::string &name, u32 &val,
743 FlagDesc *flagdesc) const
748 flags = getFlagStr(name, flagdesc, &flagmask);
754 } catch (SettingNotFoundException &e) {
764 bool Settings::setEntry(const std::string &name, const void *data,
765 bool set_group, bool set_default)
767 Settings *old_group = NULL;
769 if (!checkNameValid(name))
771 if (!set_group && !checkValueValid(*(const std::string *)data))
775 MutexAutoLock lock(m_mutex);
777 SettingsEntry &entry = set_default ? m_defaults[name] : m_settings[name];
778 old_group = entry.group;
780 entry.value = set_group ? "" : *(const std::string *)data;
781 entry.group = set_group ? *(Settings **)data : NULL;
782 entry.is_group = set_group;
791 bool Settings::set(const std::string &name, const std::string &value)
793 if (!setEntry(name, &value, false, false))
801 bool Settings::setDefault(const std::string &name, const std::string &value)
803 return setEntry(name, &value, false, true);
807 bool Settings::setGroup(const std::string &name, Settings *group)
809 return setEntry(name, &group, true, false);
813 bool Settings::setGroupDefault(const std::string &name, Settings *group)
815 return setEntry(name, &group, true, true);
819 bool Settings::setBool(const std::string &name, bool value)
821 return set(name, value ? "true" : "false");
825 bool Settings::setS16(const std::string &name, s16 value)
827 return set(name, itos(value));
831 bool Settings::setU16(const std::string &name, u16 value)
833 return set(name, itos(value));
837 bool Settings::setS32(const std::string &name, s32 value)
839 return set(name, itos(value));
843 bool Settings::setU64(const std::string &name, u64 value)
845 std::ostringstream os;
847 return set(name, os.str());
851 bool Settings::setFloat(const std::string &name, float value)
853 return set(name, ftos(value));
857 bool Settings::setV2F(const std::string &name, v2f value)
859 std::ostringstream os;
860 os << "(" << value.X << "," << value.Y << ")";
861 return set(name, os.str());
865 bool Settings::setV3F(const std::string &name, v3f value)
867 std::ostringstream os;
868 os << "(" << value.X << "," << value.Y << "," << value.Z << ")";
869 return set(name, os.str());
873 bool Settings::setFlagStr(const std::string &name, u32 flags,
874 const FlagDesc *flagdesc, u32 flagmask)
876 return set(name, writeFlagString(flags, flagdesc, flagmask));
880 bool Settings::setStruct(const std::string &name, const std::string &format,
883 std::string structstr;
884 if (!serializeStructToString(&structstr, format, value))
887 return set(name, structstr);
891 bool Settings::setNoiseParams(const std::string &name,
892 const NoiseParams &np, bool set_default)
894 Settings *group = new Settings;
896 group->setFloat("offset", np.offset);
897 group->setFloat("scale", np.scale);
898 group->setV3F("spread", np.spread);
899 group->setS32("seed", np.seed);
900 group->setU16("octaves", np.octaves);
901 group->setFloat("persistence", np.persist);
902 group->setFloat("lacunarity", np.lacunarity);
903 group->setFlagStr("flags", np.flags, flagdesc_noiseparams, np.flags);
905 return setEntry(name, &group, true, set_default);
909 bool Settings::remove(const std::string &name)
911 // Lock as short as possible, unlock before doCallbacks()
914 SettingEntries::iterator it = m_settings.find(name);
915 if (it != m_settings.end()) {
916 delete it->second.group;
917 m_settings.erase(it);
929 void Settings::clear()
931 MutexAutoLock lock(m_mutex);
935 void Settings::clearDefaults()
937 MutexAutoLock lock(m_mutex);
938 clearDefaultsNoLock();
941 void Settings::updateValue(const Settings &other, const std::string &name)
946 MutexAutoLock lock(m_mutex);
949 m_settings[name] = other.get(name);
950 } catch (SettingNotFoundException &e) {
955 void Settings::update(const Settings &other)
960 MutexAutoLock lock(m_mutex);
961 MutexAutoLock lock2(other.m_mutex);
967 SettingsParseEvent Settings::parseConfigObject(const std::string &line,
968 const std::string &end, std::string &name, std::string &value)
970 std::string trimmed_line = trim(line);
972 if (trimmed_line.empty())
974 if (trimmed_line[0] == '#')
976 if (trimmed_line == end)
979 size_t pos = trimmed_line.find('=');
980 if (pos == std::string::npos)
983 name = trim(trimmed_line.substr(0, pos));
984 value = trim(trimmed_line.substr(pos + 1));
988 if (value == "\"\"\"")
989 return SPE_MULTILINE;
995 void Settings::updateNoLock(const Settings &other)
997 m_settings.insert(other.m_settings.begin(), other.m_settings.end());
998 m_defaults.insert(other.m_defaults.begin(), other.m_defaults.end());
1002 void Settings::clearNoLock()
1005 for (SettingEntries::const_iterator it = m_settings.begin();
1006 it != m_settings.end(); ++it)
1007 delete it->second.group;
1010 clearDefaultsNoLock();
1013 void Settings::clearDefaultsNoLock()
1015 for (SettingEntries::const_iterator it = m_defaults.begin();
1016 it != m_defaults.end(); ++it)
1017 delete it->second.group;
1022 void Settings::registerChangedCallback(const std::string &name,
1023 SettingsChangedCallback cbf, void *userdata)
1025 MutexAutoLock lock(m_callback_mutex);
1026 m_callbacks[name].emplace_back(cbf, userdata);
1029 void Settings::deregisterChangedCallback(const std::string &name,
1030 SettingsChangedCallback cbf, void *userdata)
1032 MutexAutoLock lock(m_callback_mutex);
1033 SettingsCallbackMap::iterator it_cbks = m_callbacks.find(name);
1035 if (it_cbks != m_callbacks.end()) {
1036 SettingsCallbackList &cbks = it_cbks->second;
1038 SettingsCallbackList::iterator position =
1039 std::find(cbks.begin(), cbks.end(), std::make_pair(cbf, userdata));
1041 if (position != cbks.end())
1042 cbks.erase(position);
1046 void Settings::doCallbacks(const std::string &name) const
1048 MutexAutoLock lock(m_callback_mutex);
1050 SettingsCallbackMap::const_iterator it_cbks = m_callbacks.find(name);
1051 if (it_cbks != m_callbacks.end()) {
1052 SettingsCallbackList::const_iterator it;
1053 for (it = it_cbks->second.begin(); it != it_cbks->second.end(); ++it)
1054 (it->first)(name, it->second);