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;
93 std::string Settings::getMultiline(std::istream &is, size_t *num_lines)
101 std::getline(is, line);
102 if (line == "\"\"\"")
105 value.push_back('\n');
108 size_t len = value.size();
110 value.erase(len - 1);
119 bool Settings::readConfigFile(const char *filename)
121 std::ifstream is(filename);
125 return parseConfigLines(is, "");
129 bool Settings::parseConfigLines(std::istream &is, const std::string &end)
131 MutexAutoLock lock(m_mutex);
133 std::string line, name, value;
136 std::getline(is, line);
137 SettingsParseEvent event = parseConfigObject(line, end, name, value);
145 m_settings[name] = SettingsEntry(value);
150 Settings *group = new Settings;
151 if (!group->parseConfigLines(is, "}")) {
155 m_settings[name] = SettingsEntry(group);
159 m_settings[name] = SettingsEntry(getMultiline(is));
168 void Settings::writeLines(std::ostream &os, u32 tab_depth) const
170 MutexAutoLock lock(m_mutex);
172 for (const auto &setting_it : m_settings)
173 printEntry(os, setting_it.first, setting_it.second, tab_depth);
177 void Settings::printEntry(std::ostream &os, const std::string &name,
178 const SettingsEntry &entry, u32 tab_depth)
180 for (u32 i = 0; i != tab_depth; i++)
183 if (entry.is_group) {
184 os << name << " = {\n";
186 entry.group->writeLines(os, tab_depth + 1);
188 for (u32 i = 0; i != tab_depth; i++)
194 if (entry.value.find('\n') != std::string::npos)
195 os << "\"\"\"\n" << entry.value << "\n\"\"\"\n";
197 os << entry.value << "\n";
202 bool Settings::updateConfigObject(std::istream &is, std::ostream &os,
203 const std::string &end, u32 tab_depth)
205 SettingEntries::const_iterator it;
206 std::set<std::string> present_entries;
207 std::string line, name, value;
208 bool was_modified = false;
209 bool end_found = false;
211 // Add any settings that exist in the config file with the current value
212 // in the object if existing
213 while (is.good() && !end_found) {
214 std::getline(is, line);
215 SettingsParseEvent event = parseConfigObject(line, end, name, value);
219 os << line << (is.eof() ? "" : "\n");
223 value = getMultiline(is);
226 it = m_settings.find(name);
227 if (it != m_settings.end() &&
228 (it->second.is_group || it->second.value != value)) {
229 printEntry(os, name, it->second, tab_depth);
233 if (event == SPE_MULTILINE)
234 os << value << "\n\"\"\"\n";
236 present_entries.insert(name);
239 it = m_settings.find(name);
240 if (it != m_settings.end() && it->second.is_group) {
242 sanity_check(it->second.group != NULL);
243 was_modified |= it->second.group->updateConfigObject(is, os,
246 printEntry(os, name, it->second, tab_depth);
249 present_entries.insert(name);
252 os << line << (is.eof() ? "" : "\n");
257 // Add any settings in the object that don't exist in the config file yet
258 for (it = m_settings.begin(); it != m_settings.end(); ++it) {
259 if (present_entries.find(it->first) != present_entries.end())
262 printEntry(os, it->first, it->second, tab_depth);
270 bool Settings::updateConfigFile(const char *filename)
272 MutexAutoLock lock(m_mutex);
274 std::ifstream is(filename);
275 std::ostringstream os(std::ios_base::binary);
277 bool was_modified = updateConfigObject(is, os, "");
283 if (!fs::safeWriteToFile(filename, os.str())) {
284 errorstream << "Error writing configuration file: \""
285 << filename << "\"" << std::endl;
293 bool Settings::parseCommandLine(int argc, char *argv[],
294 std::map<std::string, ValueSpec> &allowed_options)
296 int nonopt_index = 0;
297 for (int i = 1; i < argc; i++) {
298 std::string arg_name = argv[i];
299 if (arg_name.substr(0, 2) != "--") {
300 // If option doesn't start with -, read it in as nonoptX
301 if (arg_name[0] != '-'){
302 std::string name = "nonopt";
303 name += itos(nonopt_index);
308 errorstream << "Invalid command-line parameter \""
309 << arg_name << "\": --<option> expected." << std::endl;
313 std::string name = arg_name.substr(2);
315 std::map<std::string, ValueSpec>::iterator n;
316 n = allowed_options.find(name);
317 if (n == allowed_options.end()) {
318 errorstream << "Unknown command-line parameter \""
319 << arg_name << "\"" << std::endl;
323 ValueType type = n->second.type;
327 if (type == VALUETYPE_FLAG) {
330 if ((i + 1) >= argc) {
331 errorstream << "Invalid command-line parameter \""
332 << name << "\": missing value" << std::endl;
351 const SettingsEntry &Settings::getEntry(const std::string &name) const
353 MutexAutoLock lock(m_mutex);
355 SettingEntries::const_iterator n;
356 if ((n = m_settings.find(name)) == m_settings.end()) {
357 if ((n = m_defaults.find(name)) == m_defaults.end())
358 throw SettingNotFoundException("Setting [" + name + "] not found.");
364 const SettingsEntry &Settings::getEntryDefault(const std::string &name) const
366 MutexAutoLock lock(m_mutex);
368 SettingEntries::const_iterator n;
369 if ((n = m_defaults.find(name)) == m_defaults.end()) {
370 throw SettingNotFoundException("Setting [" + name + "] not found.");
376 Settings *Settings::getGroup(const std::string &name) const
378 const SettingsEntry &entry = getEntry(name);
380 throw SettingNotFoundException("Setting [" + name + "] is not a group.");
385 const std::string &Settings::get(const std::string &name) const
387 const SettingsEntry &entry = getEntry(name);
389 throw SettingNotFoundException("Setting [" + name + "] is a group.");
394 const std::string &Settings::getDefault(const std::string &name) const
396 const SettingsEntry &entry = getEntryDefault(name);
398 throw SettingNotFoundException("Setting [" + name + "] is a group.");
403 bool Settings::getBool(const std::string &name) const
405 return is_yes(get(name));
409 u16 Settings::getU16(const std::string &name) const
411 return stoi(get(name), 0, 65535);
415 s16 Settings::getS16(const std::string &name) const
417 return stoi(get(name), -32768, 32767);
421 u32 Settings::getU32(const std::string &name) const
423 return (u32) stoi(get(name));
426 s32 Settings::getS32(const std::string &name) const
428 return stoi(get(name));
432 float Settings::getFloat(const std::string &name) const
434 return stof(get(name));
438 u64 Settings::getU64(const std::string &name) const
441 std::string s = get(name);
442 std::istringstream ss(s);
448 v2f Settings::getV2F(const std::string &name) const
453 value.X = stof(f.next(","));
454 value.Y = stof(f.next(")"));
459 v3f Settings::getV3F(const std::string &name) const
464 value.X = stof(f.next(","));
465 value.Y = stof(f.next(","));
466 value.Z = stof(f.next(")"));
471 u32 Settings::getFlagStr(const std::string &name, const FlagDesc *flagdesc,
474 std::string val = get(name);
475 return std::isdigit(val[0])
477 : readFlagString(val, flagdesc, flagmask);
481 // N.B. if getStruct() is used to read a non-POD aggregate type,
482 // the behavior is undefined.
483 bool Settings::getStruct(const std::string &name, const std::string &format,
484 void *out, size_t olen) const
490 } catch (SettingNotFoundException &e) {
494 if (!deSerializeStringToStruct(valstr, format, out, olen))
501 bool Settings::getNoiseParams(const std::string &name, NoiseParams &np) const
503 return getNoiseParamsFromGroup(name, np) || getNoiseParamsFromValue(name, np);
507 bool Settings::getNoiseParamsFromValue(const std::string &name,
508 NoiseParams &np) const
512 if (!getNoEx(name, value))
517 np.offset = stof(f.next(","));
518 np.scale = stof(f.next(","));
520 np.spread.X = stof(f.next(","));
521 np.spread.Y = stof(f.next(","));
522 np.spread.Z = stof(f.next(")"));
524 np.seed = stoi(f.next(","));
525 np.octaves = stoi(f.next(","));
526 np.persist = stof(f.next(","));
528 std::string optional_params = f.next("");
529 if (!optional_params.empty())
530 np.lacunarity = stof(optional_params);
536 bool Settings::getNoiseParamsFromGroup(const std::string &name,
537 NoiseParams &np) const
539 Settings *group = NULL;
541 if (!getGroupNoEx(name, group))
544 group->getFloatNoEx("offset", np.offset);
545 group->getFloatNoEx("scale", np.scale);
546 group->getV3FNoEx("spread", np.spread);
547 group->getS32NoEx("seed", np.seed);
548 group->getU16NoEx("octaves", np.octaves);
549 group->getFloatNoEx("persistence", np.persist);
550 group->getFloatNoEx("lacunarity", np.lacunarity);
553 if (!group->getFlagStrNoEx("flags", np.flags, flagdesc_noiseparams))
554 np.flags = NOISE_FLAG_DEFAULTS;
560 bool Settings::exists(const std::string &name) const
562 MutexAutoLock lock(m_mutex);
564 return (m_settings.find(name) != m_settings.end() ||
565 m_defaults.find(name) != m_defaults.end());
569 std::vector<std::string> Settings::getNames() const
571 std::vector<std::string> names;
572 for (const auto &settings_it : m_settings) {
573 names.push_back(settings_it.first);
580 /***************************************
581 * Getters that don't throw exceptions *
582 ***************************************/
584 bool Settings::getEntryNoEx(const std::string &name, SettingsEntry &val) const
587 val = getEntry(name);
589 } catch (SettingNotFoundException &e) {
595 bool Settings::getEntryDefaultNoEx(const std::string &name, SettingsEntry &val) const
598 val = getEntryDefault(name);
600 } catch (SettingNotFoundException &e) {
606 bool Settings::getGroupNoEx(const std::string &name, Settings *&val) const
609 val = getGroup(name);
611 } catch (SettingNotFoundException &e) {
617 bool Settings::getNoEx(const std::string &name, std::string &val) const
622 } catch (SettingNotFoundException &e) {
628 bool Settings::getDefaultNoEx(const std::string &name, std::string &val) const
631 val = getDefault(name);
633 } catch (SettingNotFoundException &e) {
639 bool Settings::getFlag(const std::string &name) const
642 return getBool(name);
643 } catch(SettingNotFoundException &e) {
649 bool Settings::getFloatNoEx(const std::string &name, float &val) const
652 val = getFloat(name);
654 } catch (SettingNotFoundException &e) {
660 bool Settings::getU16NoEx(const std::string &name, u16 &val) const
665 } catch (SettingNotFoundException &e) {
671 bool Settings::getS16NoEx(const std::string &name, s16 &val) const
676 } catch (SettingNotFoundException &e) {
682 bool Settings::getS32NoEx(const std::string &name, s32 &val) const
687 } catch (SettingNotFoundException &e) {
693 bool Settings::getU64NoEx(const std::string &name, u64 &val) const
698 } catch (SettingNotFoundException &e) {
704 bool Settings::getV2FNoEx(const std::string &name, v2f &val) const
709 } catch (SettingNotFoundException &e) {
715 bool Settings::getV3FNoEx(const std::string &name, v3f &val) const
720 } catch (SettingNotFoundException &e) {
726 // N.B. getFlagStrNoEx() does not set val, but merely modifies it. Thus,
727 // val must be initialized before using getFlagStrNoEx(). The intention of
728 // this is to simplify modifying a flags field from a default value.
729 bool Settings::getFlagStrNoEx(const std::string &name, u32 &val,
730 FlagDesc *flagdesc) const
735 flags = getFlagStr(name, flagdesc, &flagmask);
741 } catch (SettingNotFoundException &e) {
751 bool Settings::setEntry(const std::string &name, const void *data,
752 bool set_group, bool set_default)
754 Settings *old_group = NULL;
756 if (!checkNameValid(name))
758 if (!set_group && !checkValueValid(*(const std::string *)data))
762 MutexAutoLock lock(m_mutex);
764 SettingsEntry &entry = set_default ? m_defaults[name] : m_settings[name];
765 old_group = entry.group;
767 entry.value = set_group ? "" : *(const std::string *)data;
768 entry.group = set_group ? *(Settings **)data : NULL;
769 entry.is_group = set_group;
778 bool Settings::set(const std::string &name, const std::string &value)
780 if (!setEntry(name, &value, false, false))
788 bool Settings::setDefault(const std::string &name, const std::string &value)
790 return setEntry(name, &value, false, true);
794 bool Settings::setGroup(const std::string &name, Settings *group)
796 return setEntry(name, &group, true, false);
800 bool Settings::setGroupDefault(const std::string &name, Settings *group)
802 return setEntry(name, &group, true, true);
806 bool Settings::setBool(const std::string &name, bool value)
808 return set(name, value ? "true" : "false");
812 bool Settings::setS16(const std::string &name, s16 value)
814 return set(name, itos(value));
818 bool Settings::setU16(const std::string &name, u16 value)
820 return set(name, itos(value));
824 bool Settings::setS32(const std::string &name, s32 value)
826 return set(name, itos(value));
830 bool Settings::setU64(const std::string &name, u64 value)
832 std::ostringstream os;
834 return set(name, os.str());
838 bool Settings::setFloat(const std::string &name, float value)
840 return set(name, ftos(value));
844 bool Settings::setV2F(const std::string &name, v2f value)
846 std::ostringstream os;
847 os << "(" << value.X << "," << value.Y << ")";
848 return set(name, os.str());
852 bool Settings::setV3F(const std::string &name, v3f value)
854 std::ostringstream os;
855 os << "(" << value.X << "," << value.Y << "," << value.Z << ")";
856 return set(name, os.str());
860 bool Settings::setFlagStr(const std::string &name, u32 flags,
861 const FlagDesc *flagdesc, u32 flagmask)
863 return set(name, writeFlagString(flags, flagdesc, flagmask));
867 bool Settings::setStruct(const std::string &name, const std::string &format,
870 std::string structstr;
871 if (!serializeStructToString(&structstr, format, value))
874 return set(name, structstr);
878 bool Settings::setNoiseParams(const std::string &name,
879 const NoiseParams &np, bool set_default)
881 Settings *group = new Settings;
883 group->setFloat("offset", np.offset);
884 group->setFloat("scale", np.scale);
885 group->setV3F("spread", np.spread);
886 group->setS32("seed", np.seed);
887 group->setU16("octaves", np.octaves);
888 group->setFloat("persistence", np.persist);
889 group->setFloat("lacunarity", np.lacunarity);
890 group->setFlagStr("flags", np.flags, flagdesc_noiseparams, np.flags);
892 return setEntry(name, &group, true, set_default);
896 bool Settings::remove(const std::string &name)
898 MutexAutoLock lock(m_mutex);
900 SettingEntries::iterator it = m_settings.find(name);
901 if (it != m_settings.end()) {
902 delete it->second.group;
903 m_settings.erase(it);
911 void Settings::clear()
913 MutexAutoLock lock(m_mutex);
917 void Settings::clearDefaults()
919 MutexAutoLock lock(m_mutex);
920 clearDefaultsNoLock();
923 void Settings::updateValue(const Settings &other, const std::string &name)
928 MutexAutoLock lock(m_mutex);
931 m_settings[name] = other.get(name);
932 } catch (SettingNotFoundException &e) {
937 void Settings::update(const Settings &other)
942 MutexAutoLock lock(m_mutex);
943 MutexAutoLock lock2(other.m_mutex);
949 SettingsParseEvent Settings::parseConfigObject(const std::string &line,
950 const std::string &end, std::string &name, std::string &value)
952 std::string trimmed_line = trim(line);
954 if (trimmed_line.empty())
956 if (trimmed_line[0] == '#')
958 if (trimmed_line == end)
961 size_t pos = trimmed_line.find('=');
962 if (pos == std::string::npos)
965 name = trim(trimmed_line.substr(0, pos));
966 value = trim(trimmed_line.substr(pos + 1));
970 if (value == "\"\"\"")
971 return SPE_MULTILINE;
977 void Settings::updateNoLock(const Settings &other)
979 m_settings.insert(other.m_settings.begin(), other.m_settings.end());
980 m_defaults.insert(other.m_defaults.begin(), other.m_defaults.end());
984 void Settings::clearNoLock()
987 for (SettingEntries::const_iterator it = m_settings.begin();
988 it != m_settings.end(); ++it)
989 delete it->second.group;
992 clearDefaultsNoLock();
995 void Settings::clearDefaultsNoLock()
997 for (SettingEntries::const_iterator it = m_defaults.begin();
998 it != m_defaults.end(); ++it)
999 delete it->second.group;
1004 void Settings::registerChangedCallback(const std::string &name,
1005 SettingsChangedCallback cbf, void *userdata)
1007 MutexAutoLock lock(m_callback_mutex);
1008 m_callbacks[name].emplace_back(cbf, userdata);
1011 void Settings::deregisterChangedCallback(const std::string &name,
1012 SettingsChangedCallback cbf, void *userdata)
1014 MutexAutoLock lock(m_callback_mutex);
1015 SettingsCallbackMap::iterator it_cbks = m_callbacks.find(name);
1017 if (it_cbks != m_callbacks.end()) {
1018 SettingsCallbackList &cbks = it_cbks->second;
1020 SettingsCallbackList::iterator position =
1021 std::find(cbks.begin(), cbks.end(), std::make_pair(cbf, userdata));
1023 if (position != cbks.end())
1024 cbks.erase(position);
1028 void Settings::doCallbacks(const std::string &name) const
1030 MutexAutoLock lock(m_callback_mutex);
1032 SettingsCallbackMap::const_iterator it_cbks = m_callbacks.find(name);
1033 if (it_cbks != m_callbacks.end()) {
1034 SettingsCallbackList::const_iterator it;
1035 for (it = it_cbks->second.begin(); it != it_cbks->second.end(); ++it)
1036 (it->first)(name, it->second);