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 (SettingEntries::const_iterator it = m_settings.begin();
173 it != m_settings.end(); ++it)
174 printEntry(os, it->first, it->second, tab_depth);
178 void Settings::printEntry(std::ostream &os, const std::string &name,
179 const SettingsEntry &entry, u32 tab_depth)
181 for (u32 i = 0; i != tab_depth; i++)
184 if (entry.is_group) {
185 os << name << " = {\n";
187 entry.group->writeLines(os, tab_depth + 1);
189 for (u32 i = 0; i != tab_depth; i++)
195 if (entry.value.find('\n') != std::string::npos)
196 os << "\"\"\"\n" << entry.value << "\n\"\"\"\n";
198 os << entry.value << "\n";
203 bool Settings::updateConfigObject(std::istream &is, std::ostream &os,
204 const std::string &end, u32 tab_depth)
206 SettingEntries::const_iterator it;
207 std::set<std::string> present_entries;
208 std::string line, name, value;
209 bool was_modified = false;
210 bool end_found = false;
212 // Add any settings that exist in the config file with the current value
213 // in the object if existing
214 while (is.good() && !end_found) {
215 std::getline(is, line);
216 SettingsParseEvent event = parseConfigObject(line, end, name, value);
220 os << line << (is.eof() ? "" : "\n");
224 value = getMultiline(is);
227 it = m_settings.find(name);
228 if (it != m_settings.end() &&
229 (it->second.is_group || it->second.value != value)) {
230 printEntry(os, name, it->second, tab_depth);
234 if (event == SPE_MULTILINE)
235 os << value << "\n\"\"\"\n";
237 present_entries.insert(name);
240 it = m_settings.find(name);
241 if (it != m_settings.end() && it->second.is_group) {
243 sanity_check(it->second.group != NULL);
244 was_modified |= it->second.group->updateConfigObject(is, os,
247 printEntry(os, name, it->second, tab_depth);
250 present_entries.insert(name);
253 os << line << (is.eof() ? "" : "\n");
258 // Add any settings in the object that don't exist in the config file yet
259 for (it = m_settings.begin(); it != m_settings.end(); ++it) {
260 if (present_entries.find(it->first) != present_entries.end())
263 printEntry(os, it->first, it->second, tab_depth);
271 bool Settings::updateConfigFile(const char *filename)
273 MutexAutoLock lock(m_mutex);
275 std::ifstream is(filename);
276 std::ostringstream os(std::ios_base::binary);
278 bool was_modified = updateConfigObject(is, os, "");
284 if (!fs::safeWriteToFile(filename, os.str())) {
285 errorstream << "Error writing configuration file: \""
286 << filename << "\"" << std::endl;
294 bool Settings::parseCommandLine(int argc, char *argv[],
295 std::map<std::string, ValueSpec> &allowed_options)
297 int nonopt_index = 0;
298 for (int i = 1; i < argc; i++) {
299 std::string arg_name = argv[i];
300 if (arg_name.substr(0, 2) != "--") {
301 // If option doesn't start with -, read it in as nonoptX
302 if (arg_name[0] != '-'){
303 std::string name = "nonopt";
304 name += itos(nonopt_index);
309 errorstream << "Invalid command-line parameter \""
310 << arg_name << "\": --<option> expected." << std::endl;
314 std::string name = arg_name.substr(2);
316 std::map<std::string, ValueSpec>::iterator n;
317 n = allowed_options.find(name);
318 if (n == allowed_options.end()) {
319 errorstream << "Unknown command-line parameter \""
320 << arg_name << "\"" << std::endl;
324 ValueType type = n->second.type;
326 std::string value = "";
328 if (type == VALUETYPE_FLAG) {
331 if ((i + 1) >= argc) {
332 errorstream << "Invalid command-line parameter \""
333 << name << "\": missing value" << std::endl;
352 const SettingsEntry &Settings::getEntry(const std::string &name) const
354 MutexAutoLock lock(m_mutex);
356 SettingEntries::const_iterator n;
357 if ((n = m_settings.find(name)) == m_settings.end()) {
358 if ((n = m_defaults.find(name)) == m_defaults.end())
359 throw SettingNotFoundException("Setting [" + name + "] not found.");
365 Settings *Settings::getGroup(const std::string &name) const
367 const SettingsEntry &entry = getEntry(name);
369 throw SettingNotFoundException("Setting [" + name + "] is not a group.");
374 const std::string &Settings::get(const std::string &name) const
376 const SettingsEntry &entry = getEntry(name);
378 throw SettingNotFoundException("Setting [" + name + "] is a group.");
383 bool Settings::getBool(const std::string &name) const
385 return is_yes(get(name));
389 u16 Settings::getU16(const std::string &name) const
391 return stoi(get(name), 0, 65535);
395 s16 Settings::getS16(const std::string &name) const
397 return stoi(get(name), -32768, 32767);
401 u32 Settings::getU32(const std::string &name) const
403 return (u32) stoi(get(name));
406 s32 Settings::getS32(const std::string &name) const
408 return stoi(get(name));
412 float Settings::getFloat(const std::string &name) const
414 return stof(get(name));
418 u64 Settings::getU64(const std::string &name) const
421 std::string s = get(name);
422 std::istringstream ss(s);
428 v2f Settings::getV2F(const std::string &name) const
433 value.X = stof(f.next(","));
434 value.Y = stof(f.next(")"));
439 v3f Settings::getV3F(const std::string &name) const
444 value.X = stof(f.next(","));
445 value.Y = stof(f.next(","));
446 value.Z = stof(f.next(")"));
451 u32 Settings::getFlagStr(const std::string &name, const FlagDesc *flagdesc,
454 std::string val = get(name);
455 return std::isdigit(val[0])
457 : readFlagString(val, flagdesc, flagmask);
461 // N.B. if getStruct() is used to read a non-POD aggregate type,
462 // the behavior is undefined.
463 bool Settings::getStruct(const std::string &name, const std::string &format,
464 void *out, size_t olen) const
470 } catch (SettingNotFoundException &e) {
474 if (!deSerializeStringToStruct(valstr, format, out, olen))
481 bool Settings::getNoiseParams(const std::string &name, NoiseParams &np) const
483 return getNoiseParamsFromGroup(name, np) || getNoiseParamsFromValue(name, np);
487 bool Settings::getNoiseParamsFromValue(const std::string &name,
488 NoiseParams &np) const
492 if (!getNoEx(name, value))
497 np.offset = stof(f.next(","));
498 np.scale = stof(f.next(","));
500 np.spread.X = stof(f.next(","));
501 np.spread.Y = stof(f.next(","));
502 np.spread.Z = stof(f.next(")"));
504 np.seed = stoi(f.next(","));
505 np.octaves = stoi(f.next(","));
506 np.persist = stof(f.next(","));
508 std::string optional_params = f.next("");
509 if (optional_params != "")
510 np.lacunarity = stof(optional_params);
516 bool Settings::getNoiseParamsFromGroup(const std::string &name,
517 NoiseParams &np) const
519 Settings *group = NULL;
521 if (!getGroupNoEx(name, group))
524 group->getFloatNoEx("offset", np.offset);
525 group->getFloatNoEx("scale", np.scale);
526 group->getV3FNoEx("spread", np.spread);
527 group->getS32NoEx("seed", np.seed);
528 group->getU16NoEx("octaves", np.octaves);
529 group->getFloatNoEx("persistence", np.persist);
530 group->getFloatNoEx("lacunarity", np.lacunarity);
533 if (!group->getFlagStrNoEx("flags", np.flags, flagdesc_noiseparams))
534 np.flags = NOISE_FLAG_DEFAULTS;
540 bool Settings::exists(const std::string &name) const
542 MutexAutoLock lock(m_mutex);
544 return (m_settings.find(name) != m_settings.end() ||
545 m_defaults.find(name) != m_defaults.end());
549 std::vector<std::string> Settings::getNames() const
551 std::vector<std::string> names;
552 for (SettingEntries::const_iterator i = m_settings.begin();
553 i != m_settings.end(); ++i) {
554 names.push_back(i->first);
561 /***************************************
562 * Getters that don't throw exceptions *
563 ***************************************/
565 bool Settings::getEntryNoEx(const std::string &name, SettingsEntry &val) const
568 val = getEntry(name);
570 } catch (SettingNotFoundException &e) {
576 bool Settings::getGroupNoEx(const std::string &name, Settings *&val) const
579 val = getGroup(name);
581 } catch (SettingNotFoundException &e) {
587 bool Settings::getNoEx(const std::string &name, std::string &val) const
592 } catch (SettingNotFoundException &e) {
598 bool Settings::getFlag(const std::string &name) const
601 return getBool(name);
602 } catch(SettingNotFoundException &e) {
608 bool Settings::getFloatNoEx(const std::string &name, float &val) const
611 val = getFloat(name);
613 } catch (SettingNotFoundException &e) {
619 bool Settings::getU16NoEx(const std::string &name, u16 &val) const
624 } catch (SettingNotFoundException &e) {
630 bool Settings::getS16NoEx(const std::string &name, s16 &val) const
635 } catch (SettingNotFoundException &e) {
641 bool Settings::getS32NoEx(const std::string &name, s32 &val) const
646 } catch (SettingNotFoundException &e) {
652 bool Settings::getU64NoEx(const std::string &name, u64 &val) const
657 } catch (SettingNotFoundException &e) {
663 bool Settings::getV2FNoEx(const std::string &name, v2f &val) const
668 } catch (SettingNotFoundException &e) {
674 bool Settings::getV3FNoEx(const std::string &name, v3f &val) const
679 } catch (SettingNotFoundException &e) {
685 // N.B. getFlagStrNoEx() does not set val, but merely modifies it. Thus,
686 // val must be initialized before using getFlagStrNoEx(). The intention of
687 // this is to simplify modifying a flags field from a default value.
688 bool Settings::getFlagStrNoEx(const std::string &name, u32 &val,
689 FlagDesc *flagdesc) const
694 flags = getFlagStr(name, flagdesc, &flagmask);
700 } catch (SettingNotFoundException &e) {
710 bool Settings::setEntry(const std::string &name, const void *data,
711 bool set_group, bool set_default)
713 Settings *old_group = NULL;
715 if (!checkNameValid(name))
717 if (!set_group && !checkValueValid(*(const std::string *)data))
721 MutexAutoLock lock(m_mutex);
723 SettingsEntry &entry = set_default ? m_defaults[name] : m_settings[name];
724 old_group = entry.group;
726 entry.value = set_group ? "" : *(const std::string *)data;
727 entry.group = set_group ? *(Settings **)data : NULL;
728 entry.is_group = set_group;
737 bool Settings::set(const std::string &name, const std::string &value)
739 if (!setEntry(name, &value, false, false))
747 bool Settings::setDefault(const std::string &name, const std::string &value)
749 return setEntry(name, &value, false, true);
753 bool Settings::setGroup(const std::string &name, Settings *group)
755 return setEntry(name, &group, true, false);
759 bool Settings::setGroupDefault(const std::string &name, Settings *group)
761 return setEntry(name, &group, true, true);
765 bool Settings::setBool(const std::string &name, bool value)
767 return set(name, value ? "true" : "false");
771 bool Settings::setS16(const std::string &name, s16 value)
773 return set(name, itos(value));
777 bool Settings::setU16(const std::string &name, u16 value)
779 return set(name, itos(value));
783 bool Settings::setS32(const std::string &name, s32 value)
785 return set(name, itos(value));
789 bool Settings::setU64(const std::string &name, u64 value)
791 std::ostringstream os;
793 return set(name, os.str());
797 bool Settings::setFloat(const std::string &name, float value)
799 return set(name, ftos(value));
803 bool Settings::setV2F(const std::string &name, v2f value)
805 std::ostringstream os;
806 os << "(" << value.X << "," << value.Y << ")";
807 return set(name, os.str());
811 bool Settings::setV3F(const std::string &name, v3f value)
813 std::ostringstream os;
814 os << "(" << value.X << "," << value.Y << "," << value.Z << ")";
815 return set(name, os.str());
819 bool Settings::setFlagStr(const std::string &name, u32 flags,
820 const FlagDesc *flagdesc, u32 flagmask)
822 return set(name, writeFlagString(flags, flagdesc, flagmask));
826 bool Settings::setStruct(const std::string &name, const std::string &format,
829 std::string structstr;
830 if (!serializeStructToString(&structstr, format, value))
833 return set(name, structstr);
837 bool Settings::setNoiseParams(const std::string &name,
838 const NoiseParams &np, bool set_default)
840 Settings *group = new Settings;
842 group->setFloat("offset", np.offset);
843 group->setFloat("scale", np.scale);
844 group->setV3F("spread", np.spread);
845 group->setS32("seed", np.seed);
846 group->setU16("octaves", np.octaves);
847 group->setFloat("persistence", np.persist);
848 group->setFloat("lacunarity", np.lacunarity);
849 group->setFlagStr("flags", np.flags, flagdesc_noiseparams, np.flags);
851 return setEntry(name, &group, true, set_default);
855 bool Settings::remove(const std::string &name)
857 MutexAutoLock lock(m_mutex);
859 SettingEntries::iterator it = m_settings.find(name);
860 if (it != m_settings.end()) {
861 delete it->second.group;
862 m_settings.erase(it);
870 void Settings::clear()
872 MutexAutoLock lock(m_mutex);
876 void Settings::clearDefaults()
878 MutexAutoLock lock(m_mutex);
879 clearDefaultsNoLock();
882 void Settings::updateValue(const Settings &other, const std::string &name)
887 MutexAutoLock lock(m_mutex);
890 std::string val = other.get(name);
891 m_settings[name] = val;
892 } catch (SettingNotFoundException &e) {
897 void Settings::update(const Settings &other)
902 MutexAutoLock lock(m_mutex);
903 MutexAutoLock lock2(other.m_mutex);
909 SettingsParseEvent Settings::parseConfigObject(const std::string &line,
910 const std::string &end, std::string &name, std::string &value)
912 std::string trimmed_line = trim(line);
914 if (trimmed_line.empty())
916 if (trimmed_line[0] == '#')
918 if (trimmed_line == end)
921 size_t pos = trimmed_line.find('=');
922 if (pos == std::string::npos)
925 name = trim(trimmed_line.substr(0, pos));
926 value = trim(trimmed_line.substr(pos + 1));
930 if (value == "\"\"\"")
931 return SPE_MULTILINE;
937 void Settings::updateNoLock(const Settings &other)
939 m_settings.insert(other.m_settings.begin(), other.m_settings.end());
940 m_defaults.insert(other.m_defaults.begin(), other.m_defaults.end());
944 void Settings::clearNoLock()
947 for (SettingEntries::const_iterator it = m_settings.begin();
948 it != m_settings.end(); ++it)
949 delete it->second.group;
952 clearDefaultsNoLock();
955 void Settings::clearDefaultsNoLock()
957 for (SettingEntries::const_iterator it = m_defaults.begin();
958 it != m_defaults.end(); ++it)
959 delete it->second.group;
964 void Settings::registerChangedCallback(const std::string &name,
965 SettingsChangedCallback cbf, void *userdata)
967 MutexAutoLock lock(m_callback_mutex);
968 m_callbacks[name].push_back(std::make_pair(cbf, userdata));
971 void Settings::deregisterChangedCallback(const std::string &name,
972 SettingsChangedCallback cbf, void *userdata)
974 MutexAutoLock lock(m_callback_mutex);
975 SettingsCallbackMap::iterator it_cbks = m_callbacks.find(name);
977 if (it_cbks != m_callbacks.end()) {
978 SettingsCallbackList &cbks = it_cbks->second;
980 SettingsCallbackList::iterator position =
981 std::find(cbks.begin(), cbks.end(), std::make_pair(cbf, userdata));
983 if (position != cbks.end())
984 cbks.erase(position);
988 void Settings::doCallbacks(const std::string &name) const
990 MutexAutoLock lock(m_callback_mutex);
992 SettingsCallbackMap::const_iterator it_cbks = m_callbacks.find(name);
993 if (it_cbks != m_callbacks.end()) {
994 SettingsCallbackList::const_iterator it;
995 for (it = it_cbks->second.begin(); it != it_cbks->second.end(); ++it)
996 (it->first)(name, it->second);