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;
72 if (valid) valid = trim(name) == name;
74 errorstream << "Invalid setting name \"" << name << "\""
82 bool Settings::checkValueValid(const std::string &value)
84 if (value.substr(0, 3) == "\"\"\"" ||
85 value.find("\n\"\"\"") != std::string::npos) {
86 errorstream << "Invalid character sequence '\"\"\"' found in"
87 " setting value!" << std::endl;
94 std::string Settings::sanitizeName(const std::string &name)
96 std::string n = trim(name);
98 for (const char *s = "=\"{}#"; *s; s++)
99 n.erase(std::remove(n.begin(), n.end(), *s), n.end());
105 std::string Settings::sanitizeValue(const std::string &value)
107 std::string v(value);
110 if (v.substr(0, 3) == "\"\"\"")
113 while ((p = v.find("\n\"\"\"")) != std::string::npos)
120 std::string Settings::getMultiline(std::istream &is, size_t *num_lines)
128 std::getline(is, line);
129 if (line == "\"\"\"")
132 value.push_back('\n');
135 size_t len = value.size();
137 value.erase(len - 1);
146 bool Settings::readConfigFile(const char *filename)
148 std::ifstream is(filename);
152 return parseConfigLines(is, "");
156 bool Settings::parseConfigLines(std::istream &is, const std::string &end)
158 MutexAutoLock lock(m_mutex);
160 std::string line, name, value;
163 std::getline(is, line);
164 SettingsParseEvent event = parseConfigObject(line, end, name, value);
172 m_settings[name] = SettingsEntry(value);
177 Settings *group = new Settings;
178 if (!group->parseConfigLines(is, "}")) {
182 m_settings[name] = SettingsEntry(group);
186 m_settings[name] = SettingsEntry(getMultiline(is));
195 void Settings::writeLines(std::ostream &os, u32 tab_depth) const
197 MutexAutoLock lock(m_mutex);
199 for (SettingEntries::const_iterator it = m_settings.begin();
200 it != m_settings.end(); ++it)
201 printEntry(os, it->first, it->second, tab_depth);
205 void Settings::printEntry(std::ostream &os, const std::string &name,
206 const SettingsEntry &entry, u32 tab_depth)
208 for (u32 i = 0; i != tab_depth; i++)
211 if (entry.is_group) {
212 os << name << " = {\n";
214 entry.group->writeLines(os, tab_depth + 1);
216 for (u32 i = 0; i != tab_depth; i++)
222 if (entry.value.find('\n') != std::string::npos)
223 os << "\"\"\"\n" << entry.value << "\n\"\"\"\n";
225 os << entry.value << "\n";
230 bool Settings::updateConfigObject(std::istream &is, std::ostream &os,
231 const std::string &end, u32 tab_depth)
233 SettingEntries::const_iterator it;
234 std::set<std::string> present_entries;
235 std::string line, name, value;
236 bool was_modified = false;
237 bool end_found = false;
239 // Add any settings that exist in the config file with the current value
240 // in the object if existing
241 while (is.good() && !end_found) {
242 std::getline(is, line);
243 SettingsParseEvent event = parseConfigObject(line, end, name, value);
247 os << line << (is.eof() ? "" : "\n");
251 value = getMultiline(is);
254 it = m_settings.find(name);
255 if (it != m_settings.end() &&
256 (it->second.is_group || it->second.value != value)) {
257 printEntry(os, name, it->second, tab_depth);
261 if (event == SPE_MULTILINE)
262 os << value << "\n\"\"\"\n";
264 present_entries.insert(name);
267 it = m_settings.find(name);
268 if (it != m_settings.end() && it->second.is_group) {
270 sanity_check(it->second.group != NULL);
271 was_modified |= it->second.group->updateConfigObject(is, os,
274 printEntry(os, name, it->second, tab_depth);
277 present_entries.insert(name);
280 os << line << (is.eof() ? "" : "\n");
285 // Add any settings in the object that don't exist in the config file yet
286 for (it = m_settings.begin(); it != m_settings.end(); ++it) {
287 if (present_entries.find(it->first) != present_entries.end())
290 printEntry(os, it->first, it->second, tab_depth);
298 bool Settings::updateConfigFile(const char *filename)
300 MutexAutoLock lock(m_mutex);
302 std::ifstream is(filename);
303 std::ostringstream os(std::ios_base::binary);
305 bool was_modified = updateConfigObject(is, os, "");
311 if (!fs::safeWriteToFile(filename, os.str())) {
312 errorstream << "Error writing configuration file: \""
313 << filename << "\"" << std::endl;
321 bool Settings::parseCommandLine(int argc, char *argv[],
322 std::map<std::string, ValueSpec> &allowed_options)
324 int nonopt_index = 0;
325 for (int i = 1; i < argc; i++) {
326 std::string arg_name = argv[i];
327 if (arg_name.substr(0, 2) != "--") {
328 // If option doesn't start with -, read it in as nonoptX
329 if (arg_name[0] != '-'){
330 std::string name = "nonopt";
331 name += itos(nonopt_index);
336 errorstream << "Invalid command-line parameter \""
337 << arg_name << "\": --<option> expected." << std::endl;
341 std::string name = arg_name.substr(2);
343 std::map<std::string, ValueSpec>::iterator n;
344 n = allowed_options.find(name);
345 if (n == allowed_options.end()) {
346 errorstream << "Unknown command-line parameter \""
347 << arg_name << "\"" << std::endl;
351 ValueType type = n->second.type;
353 std::string value = "";
355 if (type == VALUETYPE_FLAG) {
358 if ((i + 1) >= argc) {
359 errorstream << "Invalid command-line parameter \""
360 << name << "\": missing value" << std::endl;
379 const SettingsEntry &Settings::getEntry(const std::string &name) const
381 MutexAutoLock lock(m_mutex);
383 SettingEntries::const_iterator n;
384 if ((n = m_settings.find(name)) == m_settings.end()) {
385 if ((n = m_defaults.find(name)) == m_defaults.end())
386 throw SettingNotFoundException("Setting [" + name + "] not found.");
392 Settings *Settings::getGroup(const std::string &name) const
394 const SettingsEntry &entry = getEntry(name);
396 throw SettingNotFoundException("Setting [" + name + "] is not a group.");
401 std::string Settings::get(const std::string &name) const
403 const SettingsEntry &entry = getEntry(name);
405 throw SettingNotFoundException("Setting [" + name + "] is a group.");
410 bool Settings::getBool(const std::string &name) const
412 return is_yes(get(name));
416 u16 Settings::getU16(const std::string &name) const
418 return stoi(get(name), 0, 65535);
422 s16 Settings::getS16(const std::string &name) const
424 return stoi(get(name), -32768, 32767);
428 s32 Settings::getS32(const std::string &name) const
430 return stoi(get(name));
434 float Settings::getFloat(const std::string &name) const
436 return stof(get(name));
440 u64 Settings::getU64(const std::string &name) const
443 std::string s = get(name);
444 std::istringstream ss(s);
450 v2f Settings::getV2F(const std::string &name) const
455 value.X = stof(f.next(","));
456 value.Y = stof(f.next(")"));
461 v3f Settings::getV3F(const std::string &name) const
466 value.X = stof(f.next(","));
467 value.Y = stof(f.next(","));
468 value.Z = stof(f.next(")"));
473 u32 Settings::getFlagStr(const std::string &name, const FlagDesc *flagdesc,
476 std::string val = get(name);
477 return std::isdigit(val[0])
479 : readFlagString(val, flagdesc, flagmask);
483 // N.B. if getStruct() is used to read a non-POD aggregate type,
484 // the behavior is undefined.
485 bool Settings::getStruct(const std::string &name, const std::string &format,
486 void *out, size_t olen) const
492 } catch (SettingNotFoundException &e) {
496 if (!deSerializeStringToStruct(valstr, format, out, olen))
503 bool Settings::getNoiseParams(const std::string &name, NoiseParams &np) const
505 return getNoiseParamsFromGroup(name, np) || getNoiseParamsFromValue(name, np);
509 bool Settings::getNoiseParamsFromValue(const std::string &name,
510 NoiseParams &np) const
514 if (!getNoEx(name, value))
519 np.offset = stof(f.next(","));
520 np.scale = stof(f.next(","));
522 np.spread.X = stof(f.next(","));
523 np.spread.Y = stof(f.next(","));
524 np.spread.Z = stof(f.next(")"));
526 np.seed = stoi(f.next(","));
527 np.octaves = stoi(f.next(","));
528 np.persist = stof(f.next(","));
530 std::string optional_params = f.next("");
531 if (optional_params != "")
532 np.lacunarity = stof(optional_params);
538 bool Settings::getNoiseParamsFromGroup(const std::string &name,
539 NoiseParams &np) const
541 Settings *group = NULL;
543 if (!getGroupNoEx(name, group))
546 group->getFloatNoEx("offset", np.offset);
547 group->getFloatNoEx("scale", np.scale);
548 group->getV3FNoEx("spread", np.spread);
549 group->getS32NoEx("seed", np.seed);
550 group->getU16NoEx("octaves", np.octaves);
551 group->getFloatNoEx("persistence", np.persist);
552 group->getFloatNoEx("lacunarity", np.lacunarity);
555 if (!group->getFlagStrNoEx("flags", np.flags, flagdesc_noiseparams))
556 np.flags = NOISE_FLAG_DEFAULTS;
562 bool Settings::exists(const std::string &name) const
564 MutexAutoLock lock(m_mutex);
566 return (m_settings.find(name) != m_settings.end() ||
567 m_defaults.find(name) != m_defaults.end());
571 std::vector<std::string> Settings::getNames() const
573 std::vector<std::string> names;
574 for (SettingEntries::const_iterator i = m_settings.begin();
575 i != m_settings.end(); ++i) {
576 names.push_back(i->first);
583 /***************************************
584 * Getters that don't throw exceptions *
585 ***************************************/
587 bool Settings::getEntryNoEx(const std::string &name, SettingsEntry &val) const
590 val = getEntry(name);
592 } catch (SettingNotFoundException &e) {
598 bool Settings::getGroupNoEx(const std::string &name, Settings *&val) const
601 val = getGroup(name);
603 } catch (SettingNotFoundException &e) {
609 bool Settings::getNoEx(const std::string &name, std::string &val) const
614 } catch (SettingNotFoundException &e) {
620 bool Settings::getFlag(const std::string &name) const
623 return getBool(name);
624 } catch(SettingNotFoundException &e) {
630 bool Settings::getFloatNoEx(const std::string &name, float &val) const
633 val = getFloat(name);
635 } catch (SettingNotFoundException &e) {
641 bool Settings::getU16NoEx(const std::string &name, u16 &val) const
646 } catch (SettingNotFoundException &e) {
652 bool Settings::getS16NoEx(const std::string &name, s16 &val) const
657 } catch (SettingNotFoundException &e) {
663 bool Settings::getS32NoEx(const std::string &name, s32 &val) const
668 } catch (SettingNotFoundException &e) {
674 bool Settings::getU64NoEx(const std::string &name, u64 &val) const
679 } catch (SettingNotFoundException &e) {
685 bool Settings::getV2FNoEx(const std::string &name, v2f &val) const
690 } catch (SettingNotFoundException &e) {
696 bool Settings::getV3FNoEx(const std::string &name, v3f &val) const
701 } catch (SettingNotFoundException &e) {
707 // N.B. getFlagStrNoEx() does not set val, but merely modifies it. Thus,
708 // val must be initialized before using getFlagStrNoEx(). The intention of
709 // this is to simplify modifying a flags field from a default value.
710 bool Settings::getFlagStrNoEx(const std::string &name, u32 &val,
711 FlagDesc *flagdesc) const
716 flags = getFlagStr(name, flagdesc, &flagmask);
722 } catch (SettingNotFoundException &e) {
732 bool Settings::setEntry(const std::string &name, const void *data,
733 bool set_group, bool set_default)
735 Settings *old_group = NULL;
737 if (!checkNameValid(name))
739 if (!set_group && !checkValueValid(*(const std::string *)data))
743 MutexAutoLock lock(m_mutex);
745 SettingsEntry &entry = set_default ? m_defaults[name] : m_settings[name];
746 old_group = entry.group;
748 entry.value = set_group ? "" : *(const std::string *)data;
749 entry.group = set_group ? *(Settings **)data : NULL;
750 entry.is_group = set_group;
759 bool Settings::set(const std::string &name, const std::string &value)
761 if (!setEntry(name, &value, false, false))
769 bool Settings::setDefault(const std::string &name, const std::string &value)
771 return setEntry(name, &value, false, true);
775 bool Settings::setGroup(const std::string &name, Settings *group)
777 return setEntry(name, &group, true, false);
781 bool Settings::setGroupDefault(const std::string &name, Settings *group)
783 return setEntry(name, &group, true, true);
787 bool Settings::setBool(const std::string &name, bool value)
789 return set(name, value ? "true" : "false");
793 bool Settings::setS16(const std::string &name, s16 value)
795 return set(name, itos(value));
799 bool Settings::setU16(const std::string &name, u16 value)
801 return set(name, itos(value));
805 bool Settings::setS32(const std::string &name, s32 value)
807 return set(name, itos(value));
811 bool Settings::setU64(const std::string &name, u64 value)
813 std::ostringstream os;
815 return set(name, os.str());
819 bool Settings::setFloat(const std::string &name, float value)
821 return set(name, ftos(value));
825 bool Settings::setV2F(const std::string &name, v2f value)
827 std::ostringstream os;
828 os << "(" << value.X << "," << value.Y << ")";
829 return set(name, os.str());
833 bool Settings::setV3F(const std::string &name, v3f value)
835 std::ostringstream os;
836 os << "(" << value.X << "," << value.Y << "," << value.Z << ")";
837 return set(name, os.str());
841 bool Settings::setFlagStr(const std::string &name, u32 flags,
842 const FlagDesc *flagdesc, u32 flagmask)
844 return set(name, writeFlagString(flags, flagdesc, flagmask));
848 bool Settings::setStruct(const std::string &name, const std::string &format,
851 std::string structstr;
852 if (!serializeStructToString(&structstr, format, value))
855 return set(name, structstr);
859 bool Settings::setNoiseParams(const std::string &name,
860 const NoiseParams &np, bool set_default)
862 Settings *group = new Settings;
864 group->setFloat("offset", np.offset);
865 group->setFloat("scale", np.scale);
866 group->setV3F("spread", np.spread);
867 group->setS32("seed", np.seed);
868 group->setU16("octaves", np.octaves);
869 group->setFloat("persistence", np.persist);
870 group->setFloat("lacunarity", np.lacunarity);
871 group->setFlagStr("flags", np.flags, flagdesc_noiseparams, np.flags);
873 return setEntry(name, &group, true, set_default);
877 bool Settings::remove(const std::string &name)
879 MutexAutoLock lock(m_mutex);
881 SettingEntries::iterator it = m_settings.find(name);
882 if (it != m_settings.end()) {
883 delete it->second.group;
884 m_settings.erase(it);
892 void Settings::clear()
894 MutexAutoLock lock(m_mutex);
898 void Settings::clearDefaults()
900 MutexAutoLock lock(m_mutex);
901 clearDefaultsNoLock();
904 void Settings::updateValue(const Settings &other, const std::string &name)
909 MutexAutoLock lock(m_mutex);
912 std::string val = other.get(name);
913 m_settings[name] = val;
914 } catch (SettingNotFoundException &e) {
919 void Settings::update(const Settings &other)
924 MutexAutoLock lock(m_mutex);
925 MutexAutoLock lock2(other.m_mutex);
931 SettingsParseEvent Settings::parseConfigObject(const std::string &line,
932 const std::string &end, std::string &name, std::string &value)
934 std::string trimmed_line = trim(line);
936 if (trimmed_line.empty())
938 if (trimmed_line[0] == '#')
940 if (trimmed_line == end)
943 size_t pos = trimmed_line.find('=');
944 if (pos == std::string::npos)
947 name = trim(trimmed_line.substr(0, pos));
948 value = trim(trimmed_line.substr(pos + 1));
952 if (value == "\"\"\"")
953 return SPE_MULTILINE;
959 void Settings::updateNoLock(const Settings &other)
961 m_settings.insert(other.m_settings.begin(), other.m_settings.end());
962 m_defaults.insert(other.m_defaults.begin(), other.m_defaults.end());
966 void Settings::clearNoLock()
969 for (SettingEntries::const_iterator it = m_settings.begin();
970 it != m_settings.end(); ++it)
971 delete it->second.group;
974 clearDefaultsNoLock();
977 void Settings::clearDefaultsNoLock()
979 for (SettingEntries::const_iterator it = m_defaults.begin();
980 it != m_defaults.end(); ++it)
981 delete it->second.group;
986 void Settings::registerChangedCallback(const std::string &name,
987 SettingsChangedCallback cbf, void *userdata)
989 MutexAutoLock lock(m_callback_mutex);
990 m_callbacks[name].push_back(std::make_pair(cbf, userdata));
993 void Settings::deregisterChangedCallback(const std::string &name,
994 SettingsChangedCallback cbf, void *userdata)
996 MutexAutoLock lock(m_callback_mutex);
997 SettingsCallbackMap::iterator it_cbks = m_callbacks.find(name);
999 if (it_cbks != m_callbacks.end()) {
1000 SettingsCallbackList &cbks = it_cbks->second;
1002 SettingsCallbackList::iterator position =
1003 std::find(cbks.begin(), cbks.end(), std::make_pair(cbf, userdata));
1005 if (position != cbks.end())
1006 cbks.erase(position);
1010 void Settings::doCallbacks(const std::string &name) const
1012 MutexAutoLock lock(m_callback_mutex);
1014 SettingsCallbackMap::const_iterator it_cbks = m_callbacks.find(name);
1015 if (it_cbks != m_callbacks.end()) {
1016 SettingsCallbackList::const_iterator it;
1017 for (it = it_cbks->second.begin(); it != it_cbks->second.end(); ++it)
1018 (it->first)(name, it->second);